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));
main_topicsandsub_topicsinclude space character in string? Where arenameandsizeproperties populated in objects?