Categories
JavaScript Answers

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

Spread the love

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("\r\n");

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 '\r\n' with join.

Conclusion

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

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *