gpt4 book ai didi

javascript - 将 json 对象嵌套到具有重复父详细信息的单个 json 对象中以构造 html 表

转载 作者:行者123 更新时间:2023-12-02 23:26:49 24 4
gpt4 key购买 nike

这是一个嵌套的 json 文件,我正在尝试将其排列为可读格式以显示在表格中

我尝试手动将所有键和值放入 for 循环中,但应该有一种优雅的方法来实现这一点,因此我达到了这样的目的。

实际的 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 有很多有用的方法来帮助你做你想做的事情。第二次您应该避免使用 .forEachfor 循环并尝试使用 Array.prototype.mapArray.prototype.reduce

关于javascript - 将 json 对象嵌套到具有重复父详细信息的单个 json 对象中以构造 html 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56699480/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com