1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| cvsToObj(csv, columnDelimiter = '\t'){ let obj = {}; let arrTable = this.csvToArray(csv, columnDelimiter); let keys = arrTable[1]; let types = arrTable[2]; for (let i = 4; i < arrTable.length; i++) { let table = arrTable[i]; if(!table[1] || table[1] == '') continue; obj[table[1]] = {ID: table[1]}; for (let j = 2; j < table.length; j++) { if(!table[j] || table[j] == '') continue; if(types[j] == 'int' || types[j] == 'float' || types[j] == 'double') obj[table[1]][keys[j]] = Number(table[j]); else obj[table[1]][keys[j]] = table[j]; } } return obj; }, csvToArray(csv, columnDelimiter = '\t') { const table = csv.trim().replace(/\r\n?/g, '\n'); let quoteCounter = 0; let lastDelimiterIndex = 0; let arrTable = [[]]; let anchorRow = arrTable[arrTable.length - 1]; for (let i = 0; i < table.length; i++) { const char = table[i]; if (char === '"' && table[i - 1] !== '\\') { quoteCounter = quoteCounter ? 0 : 1; if (quoteCounter) { lastDelimiterIndex = i + 1; } } else if ( !quoteCounter && (char === columnDelimiter || char === '\n' || i === table.length - 1) ) { const startPos = lastDelimiterIndex; let col = startPos >= i ? '' : table.slice(startPos, i).trim(); if (col[col.length - 1] === '"') { col = col.slice(0, col.length - 1); } anchorRow.push(col); lastDelimiterIndex = i + 1; if (char === '\n') { anchorRow = arrTable[arrTable.push([]) - 1]; } } } return arrTable; },
|