Home > database >  How do I convert object to text/csv in JavaScript and download as CSV?
How do I convert object to text/csv in JavaScript and download as CSV?

Time:09-29

I am trying to convert an Object to a csv in JavaScript and download it. I know the logic to download, but I don't know how to convert the Object so that it can be used for this logic.

const tests = [
    {
        id: 1,
        name: 'taro',
        designId: 1,
        designName: 'design1'
    },
    {
        id: 1,
        name: 'taro',
        designId: 2,
        designName: 'design2'
    },
    {
        id: 2,
        name: 'Bob',
        designId: 3,
        designName: 'design3'
    },
    {
        id: 2,
        name: 'Bob',
        designId: 4,
        designName: 'design4'
    },
];

The logic I'm trying to use.↓

const objToCsv = ""; // Wanted part
const type = 'text/csv';
downLoadLink.download = 'test.csv';
downLoadLink.href = URL.createObjectURL(new Blob([objToCsv], { type }));
downLoadLink.dataset.downloadurl = [type, downLoadLink.download, downLoadLink.href].join(':');
downLoadLink.click();

CodePudding user response:

One way is to use reduce function to reduce the array into a csv string:

const tests = [
    {
        id: 1,
        name: 'taro',
        designId: 1,
        designName: 'design1'
    },
    {
        id: 1,
        name: 'taro',
        designId: 2,
        designName: 'design2'
    },
    {
        id: 2,
        name: 'Bob',
        designId: 3,
        designName: 'design3'
    },
    {
        id: 2,
        name: 'Bob',
        designId: 4,
        designName: 'design4'
    },
];
const objToCsv = tests.reduce((prev, curr) => prev   '\n'   Object.values(curr), Object.keys(tests[0]));
console.log(objToCsv);

CodePudding user response:

To generate the CSV on client, you can use basic JS:

function getCsv(tests) {
    const lines = [];
    for(let item in tests) {
        const line = Object.values(item).map(x => escapeCsvValue(x));
        lines.push(line.join(";"));
    }
    return lines.join("\n");
}

function escapeCsvValue(value) {
    if(!value || value.indexOf(';') === -1)
        return value;

    return '"'   value.replace('"', '""')   '"';
}

Here is why you need to escape CSV values: Click

To export the data for saving, you can use an external library, like FileSaver.js

CodePudding user response:

A simple way to convert an ES Object to csv. Play with the code in the snippet, e.g. to add delimiters (" etc).

const tests = [
    {
        id: 1,
        name: 'taro',
        designId: 1,
        designName: 'design1'
    },
    {
        id: 1,
        name: 'taro',
        designId: 2,
        designName: 'design2'
    },
    {
        id: 2,
        name: 'Bob',
        designId: 3,
        designName: 'design3'
    },
    {
        id: 2,
        name: 'Bob',
        designId: 4,
        designName: 'design4'
    },
];

// create the topline (column headers)
let topLine = Object.keys(tests[0]).join(";");

// create lines with values
const lines = tests.reduce( (acc, val) => 
  acc.concat( Object.values(val).join(`;`) ), [] );

// concat both strings
const csv = topLine.concat(`\n${lines.join(`\n`)}`);
console.log(csv);

  • Related