Last active
March 31, 2023 15:45
-
-
Save kom50/b3d55dc4fb6133df070dc5e2160f6040 to your computer and use it in GitHub Desktop.
Convert CSV file data in Array of object using node js
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
Sr.No | Name | City | Age | |
---|---|---|---|---|
1 | Rahul | Kolkata | 21 | |
2 | Karan | Amritsar | 23 | |
3 | Priya | Bangalore | 20 |
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 fs = require('fs') | |
/** | |
* Function to convert csv file data in array of object | |
* | |
* @param {string} csvRawData - CSV file raw data | |
* @returns {[]} - Returns array of object | |
*/ | |
function csvToArray(csvRawData) { | |
// Get data as array format | |
const data = csvRawData.split('\n'); | |
let headers = []; | |
const arrayWithObj = [] | |
data.forEach((row, index) => { | |
if (!index) headers = row.trim().split(',').map(header => header.trim()) | |
else { | |
row = row.trim().split(',').map(cellData => cellData.trim()) | |
let rowData = {} | |
headers.forEach((header, headerValueIndex) => { | |
rowData = { | |
...rowData, | |
[header]: row[headerValueIndex] | |
} | |
}) | |
arrayWithObj.push(rowData); | |
} | |
}) | |
return arrayWithObj; | |
} | |
const rawData = fs.readFileSync('./data.csv', "utf-8") | |
const data = csvToArray(rawData) | |
console.log(data) | |
/* | |
Result: | |
[ | |
{ 'Sr.No': '1', Name: 'Rahul', City: 'Kolkata', Age: '21' }, | |
{ 'Sr.No': '2', Name: 'Karan', City: 'Amritsar', Age: '23' }, | |
{ 'Sr.No': '3', Name: 'Priya', City: 'Bangalore', Age: '20' } | |
] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment