首页 > 解决方案 > 使用 JavaScript 将对象数组转换为 TSV 格式(无在线工具)

问题描述

大批:

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

TSV 格式:

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

我用谷歌搜索过,但大多数情况下我找到了上面的在线工具。任何人都可以为此建议脚本,在此先感谢。

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

标签: javascriptarrayscsv

解决方案


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; ]


推荐阅读