如何从 javascript 中的嵌套对象下载 CSV?

How to download CSV from a nested object in javascript?

我想遍历 Javascript 中的一个对象并从其内部对象创建一个 CSV 文件。

const list = {
    "right": {
        "label": "Right",
        "items": ["Jack", "Dough"]
    },
    "wrong": {
        "label": "Wrong",
        "items": ["Rain", "Over"]
    },
    "nope": {
        "label": "Nope",
        "items": ["No", "Way"]
    }
};
const downLoadCsv = (list) => {
    let csvContent = '';
    Object.keys(statusM).forEach((obj) => {
      console.log(obj);
      //do something like obj.items and iterate over internal object - items
      //but typeof obj is string here
    });
    const anchorEle = document.createElement('a');
    anchorEle.href = `data:text/csv;charset=utf-8,${encodeURI(csvContent)}`;
    anchorEle.target = '_blank';
    anchorEle.download = `${key}.csv`;
    anchorEle.click();
  };

我试图遍历 obj 但我发现 typeof obj 是字符串。我更期待一个像下面这样的对象:-

    {
        "label": "Right",
        "items": ["Jack", "Dough"]
    },

我期待这样的输出:-

  Jack, Right
  Dough, Right
  Rain, Wrong
  Over, Wrong
  No, Nope
  Way, Nope

有人可以帮忙吗?

  • 因此,您需要将整个对象转换为下一个结构:
[
 ['Jack', 'Right'],
 ['Dough', 'Right'],
]
  • 它是这样完成的:Object.values(list).map(i => i.items.map(j => [j, i.label])).flat()

  • 之后我添加了额外的格式化方法toCsv - 允许换行

const list = {
    "right": {
        "label": "Right",
        "items": ["Jack", "Dough"]
    },
    "wrong": {
        "label": "Wrong",
        "items": ["Rain", "Over"]
    },
    "nope": {
        "label": "Nope",
        "items": ["No", "Way"]
    }
};

const downLoadCsv = (list) => {
    let csvContent = toCsv(Object.values(list).map(i => i.items.map(j => [j, i.label])).flat());

    const anchorEle = document.createElement('a');
    anchorEle.href = `data:text/csv;charset=utf-8,${encodeURI(csvContent)}`;
    anchorEle.target = '_blank';
    anchorEle.download = `test.csv`;
    anchorEle.click();
  };
  
  function toCsv(arr){
    return arr.reduce(function(csvString, row){
        csvString += row.join(',') ;
    csvString += "\r\n";  //";";//"\n";
        return csvString;
    }, '');
}

downLoadCsv(list)

在这里,您需要输入值而不是键,但在这里,我隐藏了不相关的内容,因为我不知道该代码。

const list = {
    "right": {
        "label": "Right",
        "items": ["Jack", "Dough"]
    },
    "wrong": {
        "label": "Wrong",
        "items": ["Rain", "Over"]
    },
    "nope": {
        "label": "Nope",
        "items": ["No", "Way"]
    }
};
const downLoadCsv = (list) => {
    let csvContent = '';
    Object.values(list).forEach((obj) => {
      console.log(obj);
      //do something like obj.items and iterate over internal object - items
      //but typeof obj is string here
    });
    /*
    const anchorEle = document.createElement('a');
    anchorEle.href = `data:text/csv;charset=utf-8,${encodeURI(csvContent)}`;
    anchorEle.target = '_blank';
    anchorEle.download = `${key}.csv`;
    anchorEle.click();
    */
  };
  
  downLoadCsv(list)