How to convert JSON to CSV format and store in a variable with JavaScript?

Sometimes, we want to convert JSON to CSV format and store in a variable with JavaScript.

In this article, we’ll look at how to convert JSON to CSV format and store in a variable with JavaScript.

How to convert JSON to CSV format and store in a variable with JavaScript?

To convert JSON to CSV format and store in a variable with JavaScript, we can use some array methods.

For instance, we write

const replacer = (key, value) => (value === null ? "" : value);
const header = Object.keys(items[0]);
const csv = [
  header.join(","),
  ...items.map((row) =>
    header
      .map((fieldName) => JSON.stringify(row[fieldName], replacer))
      .join(",")
  ),
].join("rn");

console.log(csv);

to get the header arrat with Object.keys called on the first entry in the items array.

Then we create the csv array by creating the header row with header.join(",").

Then we call items.map to map the rest of the entries in items to csv row strings.

And then we join the row strings with 'rn' with join.

Conclusion

To convert JSON to CSV format and store in a variable with JavaScript, we can use some array methods.