在javascript中动态创建嵌套数组
我需要在javascript中动态创建一个嵌套数组。阵列需要具有此结构在javascript中动态创建嵌套数组,javascript,arrays,Javascript,Arrays,我需要在javascript中动态创建一个嵌套数组。阵列需要具有此结构 { "name": "main", "children": [ { "name": "main_topic_1", "children": [ { "name": "sub_topic", "size": 422 }, { "name": "sub_topic",
{
"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_topics=['topic 1'、'topic 2'、'topic 3';
子主题=[‘子主题1’,‘子主题2’];
var a=新数组();
var b=新数组();
对于(l=0;l我发现生成动态数据结构的最简单方法是从生成输出结构开始,并内联转换输入结构,如下所示:
var output = {
name: 'main',
children: main_topics.map(topic => ({
name: topic,
children: sub_topics.map(subTopic => ({
name: subTopic,
size: 422
})
})
};
目前还不清楚您希望从哪里获得大小,或者为什么示例输出中的名称与主主题
或子主题
中的名称不匹配,但希望您能理解。我为您准备了一些东西:
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));
为什么main_topics
和sub_topics
的元素在字符串中包含空格字符?对象中填充的name
和size
属性在哪里?您可以再次使用现有的结构进行lol,您必须迭代整个对象以查找键。如果结构不一定像因此,我建议使用您想要的作为键来重新构造它,以便您可以更轻松地引用它。不幸的是,结构必须是这样,因为它提供了D3可视化。我只需要能够动态设置主题和子主题的数量;我现在知道如何命名它们。我非常擅长D3。如果您解释哪种可视化你想做的是,我可能能帮你多一点。我可能会做的是在结构中添加另一个变量,比如“active”或者诸如此类的东西到每个级别,这样你就可以在d3代码中引用它,为你的可视化提供动力。谢谢你的回答。我不认为每个主题的子主题会有什么不同。除非我遗漏了什么。你的源数据只是一个子主题名称数组;不清楚你想从哪里获得这些d不同的子主题。如果您有不同的数据源,您应该添加到问题中。非常感谢。我不得不做一些轻微的更改来处理动态变化的子主题数量,但效果非常好。感谢您的努力!