Home > Mobile >  How to work with nested loops inside nested arrays
How to work with nested loops inside nested arrays

Time:10-04


So, I'm trying to work with nested loops to search through nested arrays, to find an specific value inside those, which is "codItem". This is the test model for the array (since I can't access the original fetch request on weekends):

let teste = [{
  item: [
    {
      codItem: 'Teste1'

    }
  ]
}, {
  item: [
    {
      codItem: 'Teste2'
    }
  ]
}, {
  item: [
    {
      codItem: 'Teste3'
    }
  ]
}];

This is the code I'm trying to use, based on some fundamental concepts and videos:

var items = teste.item;
for (i = 0; len = items.length; i < len, i  ) {

  console.log(items);

  for (let properties in items[i]) {
    console.log(properties, items[i]);
  }




  var boxClonado = $("#boxMaster").clone(true);
  $(boxClonado).appendTo("#preparando").removeAttr("hidden", "style").addClass("clonados");

  $("#nomeproduto").append(teste[i].id);
  $("#quantidade").append(("Qntd.: "   teste.codItem));




}

... but at the moment, I'm getting an Uncaught TypeError: items is undefined at the first loop declaration line.

This is the last video I tried to reproduced and based the idea: https://youtu.be/AqgVLYpBWG8?t=604

Oh, the bottom part of the code refers to creating an infoBox for each item that shows up in "teste", and adding the info from "codItem" to "#nomeproduto" which is the name of the product.

Thank you in advance

CodePudding user response:

teste is an array; it has no item property. You are trying to loop through undefined, thus you get the error.

Instead, loop through each item in the array, then, inside the loop, loop through each item in the current item's item property:

let teste=[{item:[{codItem:"Teste1"}]},{item:[{codItem:"Teste2"}]},{item:[{codItem:"Teste3"}]}];

for(const items of teste){
  for(const item of items.item){
    let codItem = item.codItem;
    console.log(codItem)
  }
}

  • Related