Neha Chaudhary
Neha Chaudhary

Reputation: 1269

How to create downloadable csv file from a javascript object consisting of array?

I have an object like this:-

{
    "SUCCESS": [
        "apple",
        "orange",
        "grapes"
    ],
    "FAILED": ["kiwi"],
    "NOPE": ["peach"]
}

I want to have a CSV as follows:-

apple  SUCCESS
orange SUCCESS
grapes SUCCESS
kiwi   FAILED
peach  NOPE

I figured out this piece of code but unable to iterate over this:-

const downLoadCsv = (key, items) => {
    let csvContent = '';
    if (!items.length) {
      return;
    }
    items.forEach((item) => {
      csvContent += `${item},`;
      csvContent += '\n';
    });

    const anchorEle = document.createElement('a');
    anchorEle.href = `data:text/csv;charset=utf-8,${encodeURI(csvContent)}`;
    anchorEle.target = '_blank';
    anchorEle.download = `${key}.csv`;
    anchorEle.click();
  };

Upvotes: 0

Views: 656

Answers (1)

Emanuele Scarabattoli
Emanuele Scarabattoli

Reputation: 4469

Well, the point here is that, as you wrote, items is not an array, but an object instead.

What you should do is to iterate both items keys and the list of items for each key, so:

const downLoadCsv = (key, items) => {
  let csvContent = '';

  Object.keys(items).forEach(status => {
    items[status].forEach(fruit => {
      csvContent += `${fruit},${status}\n`;
    })
  });

  if (csvContent !== '') {
    const anchorEle = document.createElement('a');
    anchorEle.href = `data:text/csv;charset=utf-8,${encodeURI(csvContent)}`;
    anchorEle.target = '_blank';
    anchorEle.download = `${key}.csv`;
    anchorEle.click();
  }
};

Upvotes: 1

Related Questions