Converting array of JSON object to CSV format in JavaScript, with each JSON object…
- User
Converting array of JSON object to CSV format in JavaScript, with each JSON object inside array can have different keys and have overlapping keys
- Assistant
To convert an array of JSON objects to CSV format in JavaScript, you can follow these steps:
- Define a function to convert a single JSON object to a CSV row.
function convertToCSV(obj) { var csv = ''; // Extract all the keys from the object var keys = Object.keys(obj); // Iterate over the keys and extract their values for (var i = 0; i < keys.length; i++) { var key = keys[i]; // Add the key to the CSV row csv += '"' + key + '",'; // Add the value to the CSV row csv += '"' + obj[key] + '",'; } // Remove the trailing comma csv = csv.slice(0, -1); return csv + '\n'; }- Define a function to convert an array of JSON objects to CSV format.
function convertArrayToCSV(arr) { var csv = ''; // Iterate over the array and convert each object to a CSV row for (var i = 0; i < arr.length; i++) { csv += convertToCSV(arr[i]); } return csv; }- Test the function with an example array of JSON objects.
var jsonArr = [ { name: 'John', age: 30, city: 'New York' }, { name: 'Jane', age: 25, occupation: 'Teacher' }, { name: 'Sam', age: 35, city: 'Los Angeles', occupation: 'Engineer' } ]; var csvData = convertArrayToCSV(jsonArr); console.log(csvData);The
convertToCSVfunction converts a single JSON object to a CSV row by iterating over the keys of the object and appending the key-value pairs to the CSV string. TheconvertArrayToCSVfunction iterates over the array of JSON objects and callsconvertToCSVfor each object, concatenating the results into a single CSV string.Note that this implementation assumes that the values in the JSON objects are simple strings. If you have nested objects or arrays, you may need to modify the code to handle those cases appropriately.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.