json - 将对象数组转换为表格格式的数据
问题描述
我有以下对象数组:
[
{
"userId": 1,
"id": 1,
"title": "delectus aut",
"completed": false
},
{
"userId": 1,
"id": 2,
"title": "quis ut",
"completed": false
}
]
我想要以下作为输出:
userId | id | title | completed |
1 | 1 | delectus aut| false |
1 | 2 | quis ut | false |
我尝试过使用lodash,但考虑到循环的数量,我觉得我们有比这更好的解决方案:
jsonObject = response; // consider the above mention object here.
keys = _.keys(json[0]);
在这里,我发现json[0]
并非在所有情况下都相同,那么找到解决方案的最佳方法是什么。
任何帮助将不胜感激!!!
解决方案
受@Akrion 解决方案的启发,这里是修改后的版本。
有点冗长的解决方案,但这将对您有所帮助:
- 您的 JSON 数据中有不同的键
- 您在对象中有不同的键序列
- 想要在数据不可用的情况下设置默认值
const json = [
{
"userId": 1,
"id": 1,
"title": "delectus aut",
"completed": true
},
{
"completed": false,
"userId": 1,
"title": "quis ut",
"id": 2,
"extraProp": "test"
},
];
const headers = Array.from(new Set(json.reduce((acc, cur) =>
[...acc, ...Object.keys(cur)], [])));
const data = [headers];
const defaultValue = 'NA';
json.forEach(item => {
data.push(headers.reduce((acc, header) =>
acc.push(item.hasOwnProperty(header) ? item[header] : defaultValue) && acc, []));
});
console.log(data);
Stackblitz 链接:https ://stackblitz.com/edit/js-zyh1ps
推荐阅读
- kubernetes - GKE 1.16.9 Prometheus,每个 pod 的 grafana 详细信息不起作用?
- html - 如何在 Rmarkdown HTML 中定位 CSS 中的 Div
- r - 如何使用 R 中的元包更改森林图中子组的顺序?
- amazon-web-services - 在 aws ubuntu 服务器的 chmod 777 /home 上使用 chmod,现在每个 ubuntu 服务器都无法登录
- javascript - 刷新网站时随机生成的数字不会改变。我正在使用 JavaScript 和 NodeJS
- android - 使用官方插件在 Flutter 中本地验证应用程序购买中的非消耗品
- c - 如何使用 C 编程语言计算在 .txt 文件中找到的数字的最小值?
- javascript - babel 插件语法在哪里定义?
- java - macOS 上的 Java 自动使用系统代理,如何禁用它?
- javascript - 从 GmailMessage.getHeader() 访问重复的标题