我需要在 JavaScript 中动态创建一个嵌套数组。数组需要具有这种结构。
{
"name": "main",
"children": [
{
"name": "main_topic_1",
"children": [
{
"name": "sub_topic",
"size": 422
},
{
"name": "sub_topic",
"size": 422
}
]
},
{
"name": "main_topic_2",
"children": [
{
"name": "sub_topic",
"size": 422
},
{
"name": "sub_topic",
"size": 422
}
]
},
{
"name": "main_topic_3",
"children": [
{
"name": "sub_topic",
"size": 422
},
{
"name": "sub_topic",
"size": 422
}
]
}
]
}
我需要能够动态选择“main_topic_x”的数量以及属于这些相应 main_topics 的 sub_topics 数量。
我正在尝试这样的事情,但我不知道如何获得上面的结构。
main_topics = ['topic 1','topic 2','topic 3'];
sub_topics = ['subtopic 1','subtopic 2'];
var a = new Array();
var b = new Array();
for(l=0; l<main_topics.length; l++){
a[l] = b;
for(j=0; j<sub_topics.length; j++){
b[l] = sub_topics[j];
}
}
console.log(JSON.stringify(a, null, 2));
最佳答案
这是我为您整理的内容:
var JSON_Object = {name:"main", children:[]};
var main_topics = ["main_topic_1", "main_topic_2", "main_topic_3","main_topic_4"];
var sub_topics = [ {parent_topic:0, name:"sub_topic_1", size:422},
{parent_topic:0, name:"sub_topic_2", size:422},
{parent_topic:0, name:"sub_topic_3", size:212},
{parent_topic:1, name:"sub_topic_4", size:322},
{parent_topic:1, name:"sub_topic_5", size:422},
{parent_topic:2, name:"sub_topic_6", size:322},
{parent_topic:2, name:"sub_topic_7", size:125},
{parent_topic:3, name:"sub_topic_8", size:422}];
for (let i in main_topics) {
let tempObj = {name:main_topics[i], children:[]};
for (let j in sub_topics) {
if (sub_topics[j].parent_topic==i) {
tempObj.children.push({name:sub_topics[j].name,size:sub_topics[j].size});
}
}
JSON_Object.children.push(tempObj);
}
console.log(JSON.stringify(JSON_Object, null, 2));
关于javascript - 在javascript中动态创建嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41497484/