Created
November 30, 2018 16:23
-
-
Save funkyremi/c1ebd2e7a02efc93ddf41404d024f553 to your computer and use it in GitHub Desktop.
Javascript csvToJson jsonToCsv
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const jsonToCsv = (array, separator) => { | |
let result = ''; | |
for (const key in array[0]) { | |
result.length === 0 ? result += key : result += `${separator}${key}`; | |
} | |
result += '\r\n'; | |
array.forEach(line => { | |
let lineStr = ''; | |
for (const value in line) { | |
lineStr.length === 0 ? lineStr += line[value] : lineStr += `${separator}${line[value]}`; | |
} | |
result += `${lineStr}\r\n`; | |
}); | |
return result; | |
} | |
const csvToJson = (data, separator) => { | |
const csvArray = data.split('\r\n').filter(Boolean); | |
const keyNames = csvArray[0].split(separator); | |
const dataArray = csvArray.slice(1, csvArray.length - 1); | |
const result = []; | |
dataArray.forEach(d => { | |
let jsonEntryResult = {}; | |
const entries = d.split(separator); | |
keyNames.forEach((keyName, idx) => { | |
jsonEntryResult[keyName] = entries[idx]; | |
}); | |
result.push(jsonEntryResult); | |
}) | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment