Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to convert JSON object to CSV format in JavaScript?

Sometimes, we want to Convert Json Object to CSV format in JavaScript.

In this article, we’ll look at how to convert Json Object to CSV format in JavaScript.

How to convert JSON object to CSV format in JavaScript>

To Convert Json object to CSV format in JavaScript, we use the some object and array methods.

For instance, we write

const convertToCSV = (arr) => {
  const array = [Object.keys(arr[0])].concat(arr);

  return array
    .map((it) => {
      return Object.values(it).toString();
    })
    .join("\n");
};

console.log(
  convertToCSV([
    {
      id: 1,
      name: "Foo",
      timestamp: new Date(),
    },
    {
      id: 2,
      name: "Bar",
      timestamp: new Date(),
    },
    {
      id: 3,
      name: "Baz",
      timestamp: new Date(),
    },
  ])
);

to define the convertToCSV function.

In it, we get the keys from the first object in the arr array with Object.keys(arr[0]).

Then we put the keys array in an array and call concat with arr.

Next, we call array.map to return the values of the object and return an array of array with the values of each row.

We call toString to return a commas separated string with the values.

And then we call join with '\n' to join the rows together with newline.

Conclusion

To convert JSON object to CSV format in JavaScript, we use the some object and array methods.

The post How to convert JSON object to CSV format in JavaScript? appeared first on The Web Dev.



This post first appeared on The Web Dev, please read the originial post: here

Share the post

How to convert JSON object to CSV format in JavaScript?

×

Subscribe to The Web Dev

Get updates delivered right to your inbox!

Thank you for your subscription

×