Javascript在另一个循环中循环生成2个列表

时间:2017-01-05 12:11:35

标签: javascript

我有一些看起来像这样的数据:

{
    "mains": [{
        "id": "454",
        "name": "main 1",
        "subs": [{
            "id": "32",
            "name": "sub 1"
        }, {
            "id": "23",
            "name": "sub 2"
        }, {
            "id": "54",
            "name": "sub 3"
        }],
        "image": null
    }, {
        "id": "654",
        "name": "main 2",
        "subs": [{
            "id": "87",
            "name": "sub 1"
        }, {
            "id": "78",
            "name": "sub 2"
        }],
        "image": null
    }]
}

由此我需要创建2个列表:

用于创建包含所有主电源的第一个列表...我已经完成了这个:

mainlist = [];
sublist = [];

for (var i = 0; i < data.mains.length; i++) {
    var obj = data.mains[i];
    var mnlst =  obj.name;
    mainlist.push(mnlst);
}

console.log(mainlist);

在此示例中,它将返回主电源的名称,从而产生2个名称(在本例中)。

现在我需要做的是获取每个主要

的潜艇名称

所以子列表(在这种情况下将返回)

主要1的“sub 1,sub 2 and sub 3”和main 2等的“sub 1 and sub 2”......

我该怎么做?

3 个答案:

答案 0 :(得分:2)

你在问题​​标题中实际上有正确的想法 - 嵌套循环,你需要在每个“main”中迭代内部subs,如下所示:

mainlist = [];
sublist = {};
for (var i = 0; i < data.mains.length; i++) {
    var obj = data.mains[i];
    var mnlst =  obj.name;
    mainlist.push(mnlst);
    var tempArr = [];
    for(var j = 0; j < obj.subs.length ; j++){
       var subObj = obj.subs[j];
       var sblst =  subObj.name;
       tempArr.push(sblst);
    }
    sublist[mnlst] = tempArr;
}

我已将sublist更改为Object并将“subs”放入temp数组中,然后将它们插入sublist作为keyd数组(其中键是主名称)您可以像sublist['main 2']一样使用它来接收所有相关的潜艇

答案 1 :(得分:2)

您可以使用另一个数据结构作为主要name作为密钥的子列表。

var data = { "mains": [{ "id": "454", "name": "main 1", "subs": [{ "id": "32", "name": "sub 1" }, { "id": "23", "name": "sub 2" }, { "id": "54", "name": "sub 3" }], "image": null }, { "id": "654", "name": "main 2", "subs": [{ "id": "87", "name": "sub 1" }, { "id": "78", "name": "sub 2" }], "image": null }] },
    mainlist = [],
    sublist = Object.create(null);

data.mains.forEach(function (main) {
    mainlist.push(main.name);
    sublist[main.name] = main.subs.map(function (sub) {
        return sub.name;
    });
})

console.log(mainlist);
console.log(sublist['main 1']);
console.log(sublist);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)

让我们修改您的代码。

mainlist = [];
sublist = [];

for (var i = 0; i < data.mains.length; i++) {

var obj = data.mains[i];

var mnlst =  obj.name;

//--[Start Modification]--
var subArr = obj.subs;
for(var j = 0; j < subArr.length; j++)
{
 var subName = subArr[i].name;
 //Here you have subject name, do whatever you want to do with it.
}
//--[End Modification]--

 mainlist.push(mnlst);

}

console.log(mainlist);