在javascript中动态创建嵌套数组

时间:2017-01-06 01:21:33

标签: javascript arrays

我需要在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));
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

这是我为你准备的东西:

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 :(得分:0)

我发现生成动态数据结构的最简单方法是从生成输出结构开始,并内联转换输入结构,如下所示:

var output = {
  name: 'main',
  children: main_topics.map(topic => ({
    name: topic,
    children: sub_topics.map(subTopic => ({
      name: subTopic,
      size: 422
    })
  })
};

目前尚不清楚您希望从size获取main_topics或为什么样本输出中的名称与sub_topics中的名称不匹配或arrayList.remove(i),但希望你明白这一点。