juanjoDiaz / json2csv

Flexible conversion between JSON and CSV
https://juanjodiaz.github.io/json2csv/
MIT License
296 stars 32 forks source link

Unwind repeats the data when used with multiple arrays #40

Closed NerdyLuffy closed 1 year ago

NerdyLuffy commented 1 year ago
  1. Include the version of json2csv used and the interface that you are using (plainjs, node or whatwg). : On latest version v7.0.1
  2. Include your node version or your browser vendor and version. On Node 18.11.X
  3. Include the command or code you used. Here is the Link https://runkit.com/retainer2165/unwind-not-working
  4. Include your expected output and the actual output/error.

Expected Outcome is :

id author title venue address
123 author1 hello world venue1 address1
author2 venue2 address2
author3 venue3 address3
juanjoDiaz commented 1 year ago

That is not how unwind works.

You probably want a custom unwind for you specific use case:

const { Parser } = require('@json2csv/plainjs');

const customUnwind = row => 
    row.author.map((author, i) => ({
        ...(i === 0 ? { id: row.id, title: row.title } : {}),
        author,
        venue: row.venue[i],
        addresses: row.addresses[i],
    }));

const transforms = [customUnwind];
const json2csvParser = new Parser({  transforms });
const csvJudges = json2csvParser.parse(testData);
juanjoDiaz commented 1 year ago

Hey @juanjoDiaz thanks for the response, how would go about when the array size of venue is greater than author in that case it will not append the records on the csv is there a way to handle different array sizes of Author and Venue ?

const customUnwind = row => {
    const maxItems = [...Array(Math.max(row.author.length, row.venue.length, row.addresses.length)).keys()];
    return maxItems(i => ({
        ...(i === 0 ? { id: row.id, title: row.title } : {}),
        author: row.author[i] ,
        venue: row.venue[i],
        addresses: row.addresses[i],
    }));
};