-1

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++;
}
Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34
  • Add an inner loop off of the inner array. Also, if there **is** only a single property on the `data`, there's really no point in the outer loop. – Taplar Jan 03 '19 at 19:47
  • 1
    Well without seeing the JSON @Talpar is right, more than likely you need an inner loop to actually traverse the inner data. Can you add the JSON? – basic Jan 03 '19 at 19:51
  • 3
    What is `data`? – FZs Jan 03 '19 at 19:52
  • If you could show us the structure and point out what it is you're trying to loop over we can help. `data` seems to be an object and you're looping over the `keys` (`data[key]`) - but are you asking how you can loop over the values that are stored if `data[key]` is an array? – zfrisch Jan 03 '19 at 20:07
  • Possible duplicate of [How to iterate over a JavaScript object?](https://stackoverflow.com/questions/14379274/how-to-iterate-over-a-javascript-object) – Drew Reese Jan 03 '19 at 21:07

2 Answers2

0

Well, since you are use the indexes here, why not at once use a for...of loop instead? Then you don't have any need accessing the properties itself

Depending on your data object, you might need to use Object.values( data ) or stick with your previous for...in loop, but I guess the principle is clear :)

const data = {
 group1: {
  allProducts: [
    { id: 1, name: 'product 1' },
    { id: 2, name: 'product 2' },
    { id: 3, name: 'product 3' },
    { id: 4, name: 'product 4' }
  ]
 },
 group2: {
  allProducts: [
    { id: 5, name: 'product 5' }
  ]
 }
};

for (let item of Object.values( data) ) {
  for (let product of item.allProducts) {
    console.log(product);
  }
}
Icepickle
  • 12,689
  • 3
  • 34
  • 48
-1

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]);
    }
}
Michael Pratt
  • 3,438
  • 1
  • 17
  • 31