I am working on node Javascript application. I have an array, I want to transform this array into a CSV data of specific attributes.
var data =
[
{
"Name":"nom1",
"Division":"first",
"Cities":['city1','city2']
},
{
"Name":"nom2",
"Division":"first",
"Cities":['city4','city5']
}
]
I want this array to transformed to ,
Name,Cities
nom1,city1
nom1,city2
nom2,city3
nom2,city4
I tried using npm package json2csv it repeats the header on each line
script.js
const { Parser, transforms: { unwind } } = require('json2csv');
const fs = require('fs');
const path = require('path');
let outputFile = path.resolve(__dirname + path.sep + './output.csv');
const myData = [
{
"Name":"nom1",
"Division":"first",
"Cities":['city1','city2']
},
{
"Name":"nom2",
"Division":"first",
"Cities":['city4','city5']
}
]
const fields = ['Name','Cities'];
const transforms = [unwind({ paths: ['Cities'] })];
for ( i=0; i < 2; i++ ) {
const json2csvParser = new Parser({ fields, transforms });
const csv = json2csvParser.parse(myCars[i]);
fs.appendFileSync(outputFile,csv);
}
But this creates data of the form instead of what I need
"Name","Cities"
"nom1","city1"
"nom1","city2""Name","Cities"
"nom2","city4"
"nom2","city5"
My requirement is to transform the data , I am open to use any new technology or other npm package. Can anyone suggest me what to do?
myDatais an array of objects.