Search code examples
javascriptarraysjavascript-objects

Javascript Object Array loop not interrating


I have a problem with a for loop. What the problem is I have a for that is going through an object and it is only going through the array once. How can I loop through the entire object array loop? The current code is below:

var i = 0;
for (var key in data) {
  console.log(data[key].allProducts[i]);
  i++;
}

Solution

  • You only have one loop trying to control two variables, which isn't what you're trying to do. Assuming data keys are something like ['a', 'b', 'c'], you're actually getting data['a'][1], data['b'][2], data['c'][3].

    What you need is two nested loops:

    for (var key in data) {
        var productsLength = data[key].allProducts.length;
        for (var i = 0; i < productsLength; i++) {
            console.log(data[key].allProducts[i]);
        }
    }