w3resource

JavaScript: Convert an array of objects to a comma-separated values string that contains only the columns specified

JavaScript fundamental (ES6 Syntax): Exercise-5 with Solution

Write a JavaScript program to convert an array of objects to a comma-separated value (CSV) string that contains only the columns specified.

  • Use Array.prototype.join(delimiter) to combine all the names in columns to create the first row.
  • Use Array.prototype.map() and Array.prototype.reduce() to create a row for each object, substituting non-existent values with empty strings and only mapping values in columns.
  • Use Array.prototype.join('\n') to combine all rows into a string.
  • Omit the third argument, delimiter, to use a default delimiter of,.

Sample Solution:

JavaScript Code:

// Source: https://bit.ly/2neWfJ2

// Define a function called `JSON_to_CSV` that converts JSON data to CSV format.
const JSON_to_CSV = (arr, columns, delimiter = ',') =>
  [
    // Combine column titles with the delimiter.
    columns.join(delimiter),
    // Map each object in the array to a CSV row.
    ...arr.map(obj =>
      // For each object, reduce the values corresponding to the specified columns into a CSV row.
      columns.reduce(
        (acc, key) => `${acc}${!acc.length ? '' : delimiter}"${!obj[key] ? '' : obj[key]}"`, // Format value within double quotes.
        ''
      )
    )
  ].join('\n'); // Join rows with newline characters.

// Test cases
console.log(JSON_to_CSV([{ x: 100, y: 200 }, { x: 300, y: 400, z: 500 }, { x: 6 }, { y: 7 }], ['x', 'y']));
console.log(JSON_to_CSV([{ x: 100, y: 200 }, { x: 300, y: 400, z: 500 }, { x: 6 }, { y: 7 }], ['x', 'y'], ';'));

Sample Output:

x,y
"100","200"
"300","400"
"6",""
"","7"
x;y
"100";"200"
"300";"400"
"6";""
"";"7"

Flowchart:

flowchart: Convert an array of objects to a comma-separated values string that contains only the columns specified

Live Demo:

See the Pen javascript-basic-exercise-1-5 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to convert a comma-separated values (CSV) string to a 2D array of objects. The first row of the string is used as the title row.
Next: Write a JavaScript program to target a given value in a nested JSON object, based on the given key.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-5.php