Why did forEach only run out of the first value? There's no way to print it all.

suppose there is a group leader like this

 var qq = [
  
  {
    "info": {"event": 123},
    "odds": 
    [
      {"o": ["test","123",],
        "oName": " "
      },
      {"o": ["qq","ee",],
        "oName": ""
      },
    ],
    "main": true,
  },
  {
    "info": {"event": 323},
    "odds": [
      {"o": ["jk","234"] ,
        "oName": ""
      }
    ],
    "main": true,
  }
  ];

I want to print out every oName

qq.forEach(function(item,i){
  
    console.log(item.odds.oName)
    //undefined
    
    console.log(item.odds[i].oName)
    //" "
    //"TypeError: Cannot read property "oName" of undefined

  return

});


Why is it impossible to print out all the oName? How to solve it?

Apr.13,2022

dude, how about the for loop
          
           for(var i=0;i<qq.length;iPP){
                for(var j=0;j<qq[i].odds.length;jPP){
                console.log(qq[i].odds[j].oName);
                }
            }
            

clipboard.png


qq.forEach(item => {
  item.odds.forEach(val => { // oddsforEach
    console.log(val.oName)
  })
})

this certainly won't work. Odds is also an array, and the simplest and roughest thing is a double loop:

qq.forEach((item,i)=>{
    if (item.odds) {
        item.odds.forEach((val,index)=>{
            console.log(val.oName)
        })
    }
});

  1. "odds" is an array console.log (item.odds.oName) it must be undefined Ah

2.

qq.forEach((item) => {  
      item.odds.forEach((childItem) => {
         console.log(childItem.oName) 
      })
});



qq.forEach(function(item) {
    if (item.odds.length > 0) {
        item.odds.forEach(function(items, index) {
            console.log(items.oName)
        })
    }
})

forEach traverses only one layer, while the oName attribute belongs to the second layer
qq.forEach ((item) = > {

)
item.adds.map((val)=>{
    console.log(val.oName)
})

})


first of all, you can see that this is an error code. When the array executes to the second loop, there will be a undefined error:

  • first loop: item exists, item0; you can output item.odds [I] .oName; that is, the oName; of the first element of item.odds is correct.
  • second loop: item exists, iDiver1; you can output item.odds [1] .oName; that is, the oName; of the second element of item.odds, but item.odds has only one element, so a undefined error occurs.

there is a return in your forEach, which means that if you loop once, you will return, instead of looping


qq.forEach (function (item) {

)
if (item.odds.length > 0) {
    item.odds.forEach(function(items, index) {
        console.log(items.oName)
    })
}

})

Menu