Parse CSV String

Convert a CSV string to an array of objects.

Code

JavaScript
function csvToJson(csv) {
  const lines = csv.trim().split("\n");
  const headers = lines[0].split(",");
  return lines.slice(1).map((line) => {
    const values = line.split(",");
    return headers.reduce((obj, h, i) => {
      obj[h.trim()] = values[i]?.trim() ?? "";
      return obj;
    }, {});
  });
}

const csv = "name,age\nAlice,30\nBob,25";
console.log(csvToJson(csv));

Line-by-line explanation

Expected output

[{ name: "Alice", age: "30" }, { name: "Bob", age: "25" }]

Related snippets

Related DuskTools