How do I fix this javascript foreach bug?

Simon P :

I have an object in the form of

res = { 2019: 
[
{id: 1, points: 435},
{id: 830, points: 230},
...
]
}

and an array seasons which is just a bunch of years => ["2015","2016",..."2019"]

seasons.forEach(season => {
     res[season].forEach(item => {
     console.log(item);
   });
});

The snipped above logs each result correctly however I still get this error: Unhandled Rejection (TypeError): Cannot read property 'forEach' of undefined

Jon Warren :

You could use optional chaining to easily solve this. Simply add a question mark before the nested forEach, like this:

seasons.forEach(season => {
     res[season]?.forEach(item => {
     console.log(item);
   });
});

Note: As mentioned in the compatibility section of the linked doc, optional chaining is not yet supported by all browsers, so you might want to use a transpiler (like Babel)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=29765&siteId=1