Q:

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

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

//#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'], ';'));

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now