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();
1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.