I’ve converted csv based text files to arrays containing headers and rows and now I want to convert them into given below solution. Can anybody do this using methods like .map()
, .reduce()
or whatever.
Arrays I have look alike:
let header = ['a', 'b', 'c', 'd'];
let rows = ['1,2,3,4', '5,6,7,8', '9,0,1,2'];
The result I want:
[
{
a: 1,
b: 2,
c: 3,
d: 4,
},
{
a: 5,
b: 6,
c: 7,
d: 8,
},
{
a: 9,
b: 0,
c: 1,
d: 2,
},
]
I was able to do this using for loop but that wasn’t the appropriate solution for es6.
Above I’ve mentioned some dummy arrays, right now the actual code is:
const recordReader = content => {
let weatherRecords = [];
let rows = content.split('n');
let headers = rows.shift().split(',');
for (let row = 0; row < rows.length; row++) {
let weatherReading = {};
if (!rows[row]) {
continue;
}
let record = rows[row].split(',');
for (let column = 0; column < headers.length; column++) {
weatherReading[headers[column]] = record[column];
}
weatherRecords.push(weatherReading);
}
return weatherRecords;
};