0

Lets say this JSON is held inside a variable called response:

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

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

I want to access the models inside each brand for example:

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

So how can i say for each car_brands get the models( the array inside each car_brand) i.e Accord civic in the same loop.

Maybe i should structure my JSON properly to make it easier to parse.

1
  • console.log(response.brands[car_brands]) Commented May 23, 2014 at 16:13

3 Answers 3

2

You can get at the value by using the property indexer syntax:

var car_brandsArray = response.brands[car_brands]

And then you can loop over them with a for loop:

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
    }
}

Or of course, just log the array immediately:

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

when you iterate:

for(var car_brands in response.brands) {
}

you iterate the indexes (in objects) and not the values (for in iterates over properties).

finally, to get your array:

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

and to iterate over it's values:

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];
    }
}
1
for ( var car_brands in response.brands ) {
    for(var model in response.brands[car_brands]) {
        console.log(model);
    }
}

You nearly had it, just needed another loop :)

or you could do it with Array.forEach:

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

My personal favourite is Array.forEach.

Not the answer you're looking for? Browse other questions tagged or ask your own question.