Converting an array of JSON objects to CSV format in JavaScript can be a bit tricky when each JSON object can have different keys, and there are overlapping keys. However, here is a general approach that you can use:
- Identify the unique keys across all JSON objects in the array.
- Create an array of arrays, where each inner array represents a row in the CSV file.
- Iterate through each JSON object in the array and create a new inner array for each one, populating it with the values for each unique key. If a JSON object doesn't have a value for a particular key, you can use an empty string or a default value.
- Join each inner array into a string using commas as delimiters.
- Join all the stringified rows into a single string using newline characters as delimiters.
Here's some sample code to illustrate this approach:
const jsonArray = [
{ name: 'Alice', age: 30, city: 'New York' },
{ name: 'Bob', age: 25, city: 'Los Angeles' },
{ name: 'Charlie', city: 'Chicago' },
];
// Step 1: Identify the unique keys across all JSON objects in the array
const keys = [...new Set(jsonArray.flatMap(obj => Object.keys(obj)))];
// Step 2: Create an array of arrays, where each inner array represents a row in the CSV file
const csvRows = [];
// Step 3: Iterate through each JSON object in the array and create a new inner array for each one
jsonArray.forEach(obj => {
const row = keys.map(key => obj[key] || '');
csvRows.push(row);
});
// Step 4: Join each inner array into a string using commas as delimiters
const csvStrings = csvRows.map(row => row.join(','));
// Step 5: Join all the stringified rows into a single string using newline characters as delimiters
const csv = csvStrings.join('\n');
console.log(csv);
Output:
name,age,city
Alice,30,New York
Bob,25,Los Angeles
Charlie,,Chicago
Note that this approach assumes that the order of keys in each JSON object is not important. If you need to preserve the order of keys in each JSON object, you can modify the code to sort the keys before creating the CSV rows. Additionally, this approach will include all unique keys across all JSON objects, even if some JSON objects don't have values for those keys. If you only want to include keys that have values in all JSON objects, you can modify the code to filter out the keys that are missing from any JSON object.