0

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();
Lana2548
  • 39
  • 5
  • 1
    you could try this : [Converting JSON object to CSV format in JavaScript](https://stackoverflow.com/a/11257124/14526868) – Jesper Sep 29 '21 at 07:17

2 Answers2

0

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

Impworks
  • 2,647
  • 3
  • 25
  • 53
0

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);
KooiInc
  • 119,216
  • 31
  • 141
  • 177