0

I'm currently struggling to use a forEach method to loop over an array with multiple objects in it. I might be making a silly mistake but im not sure where im going wrong with this

I have an object with some arrays like this...

assistants array:

var assistants = [ { "countryCode":"US", "cityName":"San Diego", "geographicRegionCode":"CA" }, { "countryCode":"AD", "cityName":"a", "geographicRegionCode":null } ] 

function im using to loop through and return a value...

 function validateAssistants () { angular.forEach(assistants, function(a) { if(a.countryCode === "US") { return true; } }); } 

When i am going to debug...it keeps on saying that a is not defined. Not sure what i'm doing wrong. Can someone point me in the right direction?

1
  • 1
    Mostly because there is a typo here "countryCode": "AD".No comma
    – brk
    CommentedAug 22, 2018 at 16:01

1 Answer 1

1

forEach() works like [1,2,3].forEach(callback), but the best best way, in my opinion is using some() to find if some element match, like assistants.some(o=>o.countryCode == "US").

var assistants = [ { "countryCode":"US", "cityName":"San Diego", "geographicRegionCode":"CA" }, { "countryCode":"AD", "cityName":"a", "geographicRegionCode":null } ] assistants.forEach((o)=>{ if(o.countryCode === "US") { console.log(true); } }) console.log(assistants.some(o=>o.countryCode == "US"))//<-- best

forEach() iterates all elements, if you find the match at 0 position continues iterating till the end without need, some or for (with break), stops when find the match.

0

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.