【问题标题】:header values appears more than once when converting json to csv将 json 转换为 csv 时,标题值出现多次
【发布时间】:2020-01-02 08:39:23
【问题描述】:

我想知道使用 javascript 将 json 转换为 csv 时, 每次点击时,标题都会出现多次。 下面是我的代码,每次点击,标题都会增加, 如下输出所示

 convertToCSV(objArray) {
    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    var str = '';
    for (var i = 0; i < array.length; i++) {
        var line = '';
        for (var index in array[i]) {
            if (line != '') line += ','
            line += array[i][index];
        }
        str += line + '\r\n';
    }
    return str;
}

 exportCSV =() =>{
    const headers = ["Id", "Name", "City"];
    const items  = [
      [60, "xyz", "TH"],
      [62, "abc", "MY"],
      [61, "xxx", "IN"]
    ];
    const fileTitle = this.props.title;
    if (headers) {
        items.unshift(headers);
    }
    // Convert Object to JSON
    var jsonObject = JSON.stringify(items);
    console.log(jsonObject);
    var csv = this.convertToCSV(jsonObject);
    var exportedFilenmae = fileTitle + '.csv' || 'export.csv';
    var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    if (navigator.msSaveBlob) { // IE 10+
        navigator.msSaveBlob(blob, exportedFilenmae);
    } else {
        var link = document.createElement("a");
        if (link.download !== undefined) { // feature detection
            // Browsers that support HTML5 download attribute
            var url = URL.createObjectURL(blob);
            link.setAttribute("href", url);
            link.setAttribute("download", exportedFilenmae);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    }
}

在 csv 中输出,如下所示, 每次点击,标题数量都会增加

Id, Name, City
Id, Name, City
60, "xyz", "TH"
62, "abc", "MY"
61, "xxx", "IN"

【问题讨论】:

    标签: javascript jquery arrays csv object


    【解决方案1】:

    请在下面找到将 JSON 转换为 CSV 的简化代码(在我的应用程序中尝试和测试):

    var jsonData = {
      "colors": [
        {
          "color": "black",
          "category": "hue",
          "type": "primary"
        },
        {
          "color": "white",
          "category": "value"
        },
        {
          "color": "red",
          "category": "hue",
          "type": "primary"
        },
        {
          "color": "blue",
          "category": "hue",
          "type": "primary"
        },
        {
          "color": "yellow",
          "category": "hue",
          "type": "primary"
        },
        {
          "color": "green",
          "category": "hue",
          "type": "secondary"
        },
      ]
    }
    var JSONToCSVConvertor = function(JSONData, ReportTitle, ShowLabel) {
    
            let arrData = typeof JSONData != 'object' ? JSON.parse(JSONData.colors) : JSONData.colors;
            let CSV = '';
            //This condition will generate the Label/Header
            if (ShowLabel) {
                let row = "";
                //This loop will extract the label from 1st index of on array
                for (let index in arrData[0]) {
                    //Now convert each value to string and comma-seprated
                    row += index + ',';
                }
                row = row.slice(0, -1);
                //append Label row with line break
                CSV += row + '\r\n';
            }
    
            //1st loop is to extract each row
            for (let i = 0; i < arrData.length; i++) {
                let row = "";
                //2nd loop will extract each column and convert it in string comma-seprated
                for (let index in arrData[i]) {
                    row += '"' + arrData[i][index] + '",';
                }
                row.slice(0, row.length - 1);
                //add a line break after each row
                CSV += row + '\r\n';
            }
    
            if (CSV == '') {
                return;
            }
            return CSV;
        }
    console.log(JSONToCSVConvertor(jsonData, 'test', true));

    【讨论】:

      猜你喜欢
      • 2022-11-07
      • 2011-09-14
      • 1970-01-01
      • 1970-01-01
      • 2019-11-01
      • 2015-11-20
      • 1970-01-01
      • 2018-05-23
      • 2015-04-23
      相关资源
      最近更新 更多