0

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

1 Answer 1

1

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();
  }
};
Sign up to request clarification or add additional context in comments.

3 Comments

Did you run this piece of code somewhere?
No, I mean, not this code in particular, but I used the same technique to iterate over object keys and this implementation make sense to me, according to your scenario, since you need to iterate over object keys and over the list included in each key. Did you had some error?
By the way I tried now and the function works with key as a string, like "test", and items as the object you shared in your question. I get a file to download and the data were in the file as expected. If you need to improve it a little bit, eventually, you can check if Object.keys(items).length exists before to iterate the keys.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.