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
const JSON_to_CSV = (arr, columns, delimiter = ',') =>
  [
    columns.join(delimiter),
    ...arr.map(obj =>
      columns.reduce(
        (acc, key) => `${acc}${!acc.length ? '' : delimiter}"${!obj[key] ? '' : obj[key]}"`,
        ''
      )
    )
  ].join('\n');

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.



Follow us on Facebook and Twitter for latest update.