Reputation: 25
Hi have the below JSON which I would like to match against a set of field names in CSV File and populate. I am getting the json data from an api and would like to create the set CSV file on the fly in node.js
CSV set Field names:
"Name", "ID", "PRODUCT 1", "PRODUCT 2", "PRODUCT 3"
JSON (manual example for simplicity, apologies if structure has errors):
[{
name: 'Bob',
id: '100',
products: {[
{item: 'product 1',
qty: '3'},
{item: 'product 2',
qty: '2'}]
},{
name: 'James',
id: '200',
products: {[
{item: 'product 3',
qty: '1'}]
}
Desired CSV populated:
CSV Fields:
"Name", "ID", "PRODUCT 1", "PRODUCT 2", "PRODUCT 3"
Bob 100 3 2
James 200 1
Upvotes: 0
Views: 383
Reputation: 736
I would shape and flat the CSV columns, then parse and output using json2csv and fs.
const { parse } = require('json2csv');
const fs = require('fs');
const items = [
{
name: 'Bob',
id: '100',
products: [
{
item: 'product 1',
qty: '3'
},
{
item: 'product 2',
qty: '2'
}]
}, {
name: 'James',
id: '200',
products: [
{
item: 'product 3',
qty: '1'
}]
}
];
// flatten the needed CSV columns
const flatten = items.map(item => {
const i = {
name: item.name,
id: item.id
};
// pull out products
item.products.forEach(product => {
i[product.item] = product.qty;
});
return i;
});
// Declare the expected fields here
const fields = ['name', 'id', 'product 1', 'product 2', 'product 3'];
const csv = parse(flatten, { fields });
fs.writeFile('items.csv', csv, (err) => {
if (err) throw err;
console.log('CSV file saved');
});
Hope I've helped.
Upvotes: 1