javascript - 将 json 对象嵌套到具有重复父详细信息的单个 json 对象中以构造 html 表
问题描述
这是一个嵌套的 json 文件,我正在尝试以可读格式排列它以显示在表格中
我尝试手动将所有键和值放入 for 循环中,但应该有一种优雅的方式来实现这一点,因此我达到了 SO。
实际的 JSON 是一个非常嵌套的 JSON,需要时间来执行 500k 行的数据
结果应该是增强的 JSON,父值也出现在子值中
var property = {
"data": [{
"ID": "123456",
"name": "Coleridge st",
"criteria": [
{
"type": "type1",
"name": "name1",
"value": "7",
"properties": []
},
{
"type": "type2",
"name": "name2",
"value": "6",
"properties": [
{
"type": "MAX",
"name": "one",
"value": "100"
}, {
"type": "MIN",
"name": "five",
"value": "5"
}
]
},
{
"type": "type3",
"name": "name3",
"value": "5",
"properties": [{
"type": "MAX1",
"name": "one6",
"value": "1006"
}, {
"type": "MIN2",
"name": "five6",
"value": "56"
}]
}
]
},
{
"ID": "456789",
"name": "New Jersy",
"criteria": [
{
"type": "type4",
"name": "name4",
"value": "6",
"properties": [{
"type": "MAX12",
"name": "one12",
"value": "10012"
}, {
"type": "MIN23",
"name": "five12",
"value": "532"
}]
}
]
}]
};
var output = [];
property.data.forEach(function (users) {
var multirows = {
id: users.ID,
name: users.name,
};
for (var i = 0; i < users.criteria.length; i++) {
var criterias = {
type: users.criteria[i].type,
name: users.criteria[i].name,
value: users.criteria[i].value,
}
var mat_contacts_rows;
if (!isEmpty(users.criteria[i].properties)) {
for (var j = 0; j < users.criteria[i].properties.length; j++) {
var property = {
type: users.criteria[i].properties[j].type,
name: users.criteria[i].properties[j].name,
value: users.criteria[i].properties[j].value
};
mat_contacts_rows = { ...multirows, ...{ criteria: criterias }, ...{ properties: property } };
output.push(mat_contacts_rows);
}
} else {
var property = [];
mat_contacts_rows = { ...multirows, ...{ criteria: criterias }, ...{ properties: property } };
output.push(mat_contacts_rows);
}
}
});
console.log(JSON.stringify(output, undefined, 2))
function isEmpty(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key))
return false;
}
return true;
}
解决方案
我认为这对你来说可能是一个很好的练习,不回答你的问题,而是给你一些提示。你应该首先看看:Lodash wish 有一堆有用的方法来帮助你做你想做的事情。在第二次你应该避免使用.forEach
orfor
循环并尝试使用Array.prototype.map或Array.prototype.reduce
推荐阅读
- pycharm - 如何防止这种情况:我将焦点切换到不同的应用程序(alt+tab),切换回 Pycharm,然后项目树崩溃?
- paypal - 客户贝宝按钮购买后更改谷歌驱动器链接
- php - 为什么有些电子邮件 ID 被接受而有些不是 PHP
- python - 使用返回看不到结果
- android - 字段重叠,以编程方式创建布局
- ruby-on-rails - 通过层次结构获取平均总和
- java - 如何在 JavaDoc 中链接 com.android.Volley 包
- c++ - STL 的头文件
- powershell - 如何在powershell中拆分大于X的文本文件行?
- excel - VBA查找和替换到不同的列,同一行,SKIP IF Cell有一个值