【问题标题】:Convert array of objects to TSV format using JavaScript (No online tools)使用 JavaScript 将对象数组转换为 TSV 格式(无在线工具)
【发布时间】:2018-10-27 11:48:09
【问题描述】:

数组:

[{"username":"admin","datetime":"27/10/2018 11:27","password":"12345"}]

到

TSV 格式:

username    datetime    password
admin   27/10/2018 11:27    12345

我在 Google 上搜索过,但大多数情况下我会找到上述的在线工具。任何人都可以为此建议脚本,提前谢谢。

免责声明:我的应用程序在没有互联网的情况下工作,所以互联网依赖在这里不起作用。

【问题讨论】:

  • papaparse 可能会做你想做的事
  • 是否有任何 JavaScript sn-p 可以将对象数组转换为 TSV? Expet 插件和在线工具。

标签: javascript arrays csv


【解决方案1】:

const data = [{"username":"admin","datetime":"27/10/2018 11:27","password":"12345"},{"username":"admin2","datetime":"22/11/2018 11:27","password":"admin2"}];

// grab the column headings (separated by tabs)
const headings = Object.keys(data[0]).join('\t');

// iterate over the data
const rows = data.reduce((acc, c) => {
  
  // for each row object get its values and add tabs between them
  // then add them as a new array to the outgoing array
  return acc.concat([Object.values(c).join('\t')]);

// finally joining each row with a line break
}, []).join('\n');

// display the result (here with `innerText` because
// `textContent` doesn't recognise styling)
document.body.innerText = `${headings}\n${rows}`;
body { white-space: pre; ]

【讨论】:

    【解决方案2】:
    function convertArrayTSV() {
        let result, ctr, keys, label, columnDelimiter, lineDelimiter;
    
        let data = [{ "username": "admin", "datetime": "27/10/2018 11:27", "password": "12345" }];
    
        columnDelimiter = '  ';
        lineDelimiter = '\n';
    
        keys = Object.keys(data[0]);
        label = ["username", "datetime", "password"];
        result = '';
        result += label;
        result += lineDelimiter;
        let no = 1;
    
        data.forEach(function (item) {
            ctr = 1;
            keys.forEach(function (key) {
                if (ctr > 1) result += columnDelimiter;
                if (key === 'username') {
                    let str = item[key];
                    result += str;
                    ctr++;
                } else if (key === 'datetime') {
                    let str = item[key];
                    result += str;
                    ctr++;
                } else if (key === 'password') {
                    let str = item[key];
                    result += str;
                    ctr++;
                }
            });
            result += lineDelimiter;
            no++;
        });
    
        return result;
    }
    
    console.log(convertArrayTSV());
    

    O/P:

    username,datetime,password 
    admin  27/10/2018 11:27  12345
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-29
      • 2012-08-07
      • 2021-08-21
      • 2018-07-14
      • 2021-01-09
      • 2022-09-27
      • 2019-10-22
      相关资源
      最近更新 更多