Home > OS >  Nested forEach not finding item
Nested forEach not finding item

Time:01-20

Can anyone tell me why this nested for loop does not match on 'Greetings', which is in the JSON it is passed (on the "second level").

I have a sample StackBlitz here, see the console.

    menuItems.forEach((firstLevel) => {
      if (firstLevel.items) {
        firstLevel.items.forEach((secondLevel) => {
          if (secondLevel.items) {
            secondLevel.items.forEach((thirdLevel) => {
              console.log('L3 processing '   thirdLevel.label);
            });
            console.log('L2 processing '   secondLevel.label);
    
            if (secondLevel.label === 'Greetings') {
              console.log('Found Greetings');
            }
          }
        });
      }
      console.log('L1 processing '   firstLevel.label);
    });

CodePudding user response:

That's because your secondLevel iteration is asking for any "secondLevel" that has an items array, and the "Greetings" one does not have any "items" property

  •  Tags:  
  • Related