使用javascript访问对象内的数组?

时间:2014-05-23 16:07:07

标签: javascript json

让我们说这个JSON保存在一个名为response的变量中:

{
    "brands": {
        "Honda": [
          "Accord",
          "Civic"
        ],

        "Porsche": [
          "Cayenne",
          "Cayman"
        ]
    }
}

我想访问每个品牌内的模型,例如:

for ( var car_brands in response.brands ) {
    console.log(car_brands); // would console Honda, Porsche etc.
}

那么我怎么能说每个car_brands得到模型(每个car_brand里面的数组),即Accord civic在同一个循环中。

也许我应该正确构建我的JSON以便更容易解析。

3 个答案:

答案 0 :(得分:2)

您可以使用属性索引器语法来获取值:

var car_brandsArray = response.brands[car_brands]

然后你可以用for循环遍历它们:

for ( var car_brands in response.brands ) {
    console.log(car_brands); // would console Honda, Porsche etc.
    var car_brandsArray = response.brands[car_brands];
    for (var i = 0; i < car_brandsArray .length; i++) {
        console.log(car_brandsArray[i]; // would console Accord, Civi
    }
}

当然,只需立即记录数组:

for ( var car_brands in response.brands ) {
        console.log(car_brands); // would console Honda, Porsche etc.
        var car_brandsArray = response.brands[car_brands];
        console.log(car_brandsArray);
    }

答案 1 :(得分:1)

for ( var car_brands in response.brands ) {
    for(var model in response.brands[car_brands]) {
        console.log(model);
    }
}

你几乎拥有它,只需要另一个循环:)

或者您可以使用Array.forEach执行此操作:

response.brands.forEach(function (brand) {
    brand.forEach(function (model) {
        console.log(model);
    });
});

我个人最喜欢的是Array.forEach。

答案 2 :(得分:1)

迭代时

for(var car_brands in response.brands) {
}

迭代索引(在对象中)而不是值(for in迭代属性)。

最后,获取你的数组:

for(var car_brand in response.brands) {
    var car_brands = response.brands[car_brand];
}

并迭代它的值:

for(var car_brand in response.brands) {
    var car_brands = response.brands[car_brand];
    for(var index = 0; index < car_brands.length; i++) {
        //do anything here, over car_brands[index];
    }
}