I need to dynamically create a nested array in javascript. The array needs to have this structure.
{
"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
}
]
}
]
}
I need to be able to dynamically choose the number of "main_topic_x" as well as the number of sub_topics that belong to those respective main_topics.
I am trying something like this, but I don't know how to get the structure as above.
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));
2 Answers 2
Here's something I put together for you:
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));
1 Comment
I find the easiest way to produce a dynamic data structure is to start by producing the output structure, and transform the input structures inline, like this:
var output = {
name: 'main',
children: main_topics.map(topic => ({
name: topic,
children: sub_topics.map(subTopic => ({
name: subTopic,
size: 422
})
})
};
It's not clear where you're expecting to get size from or why the names in your sample output don't match what's in main_topics or sub_topics, but hopefully you get the idea.
main_topicsandsub_topicsinclude space character in string? Where arenameandsizeproperties populated in objects?