Convert JSON Array to CSV
Convert an array of objects to a CSV string.
Code
JavaScript
function jsonToCsv(arr) {
if (arr.length === 0) return "";
const headers = Object.keys(arr[0]);
const rows = arr.map((obj) =>
headers.map((h) => `"${String(obj[h] ?? "").replace(/"/g, '""')}"`).join(",")
);
return [headers.join(","), ...rows].join("\n");
}
const data = [{ name: "Alice", age: 30 }, { name: "Bob", age: 25 }];
console.log(jsonToCsv(data));Line-by-line explanation
- 1.Get headers from first object keys.
- 2.Escape quotes in values by doubling them.
- 3.Wrap values in quotes for safety.
- 4.Join headers and rows with newlines.
Expected output
name,age "Alice",30 "Bob",25