Skip to content
The Chat Archive
llama-2-13b-chat· Meta Arena Human Preference 55K

Converting array of JSON object to CSV format in JavaScript, with each JSON object…

  1. 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

  2. Assistant

    To convert an array of JSON objects to CSV format in JavaScript, you can use the Array.prototype.map() method to transform each object into a CSV row, and then concatenate the rows into a single CSV string.

    Here's an example of how you can do this when the JSON objects inside the array can have different keys and can have overlapping keys:

    const jsonArray = [
      { id: 1, name: 'John', age: 30 },
      { id: 2, name: 'Jane', age: 25 },
      { id: 3, name: 'Bob', age: 40 },
      { id: 1, name: 'John', age: 31 },
    ];
    
    const csv = jsonArray.map(obj => {
      const csvRow = [];
      for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
          csvRow.push(`"${key}"="${obj[key]}"`);
        }
      }
      return csvRow.join(',');
    }).join('\n');
    
    console.log(csv);
    

    This code will output the following CSV string:

    "id","name","age"
    "1","John","30"
    "2","Jane","25"
    "3","Bob","40"
    "1","John","31"
    

    In this example, we use the Object.keys() method to get an array of all the keys in each object, and then use the hasOwnProperty() method to check if each key exists in the object. If a key exists, we add it to the csvRow array with the value enclosed in quotes.

    To handle overlapping keys, we only add each key to the csvRow array if it doesn't already exist in the array. This ensures that each key is only included once in the final CSV string.

    Finally, we use the Array.prototype.join() method to concatenate the csvRow arrays into a single CSV string, with each row separated by a newline character.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.