使用JavaScript将对象数组转换为TSV格式(无在线工具)

时间:2018-10-27 11:48:09

标签: javascript arrays csv

数组:

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

收件人

TSV格式:

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

我已经使用Google进行过搜索,但是大多数情况下我都可以找到上面的在线工具。有人可以为此建议脚本吗?

  

免责声明:我的应用程序无法连接互联网,因此此处无法使用互联网。

2 个答案:

答案 0 :(得分: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; ]

答案 1 :(得分:0)

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