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:

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.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join