0

I'm working on an angular project where I have access to a JSON feed of user data. Normally, I would call that as a service within a controller by simply doing:

userFactory.get(function (data) {
    $scope.results = data;
}

However, in one of my controllers, I need to write an if statement that checks a nested array to see if the type field has a certain value. In the example below, I'm looking for "type" : "yep".

{
   "id": 3,
   "data": stuff,
   "following": [
      {
         "id": 213,
         "type": "nope",
      },
      {
         "id": 324,
         "type": "nope",
      },
      {
         "id": 532,
         "type": "yep",
      }
   ],
}

What I need to do is search through the following object to find out whether there is any instance of "type" : "yep". I figure this is doable with underscore, but I'm not sure how. I was thinking of something along the lines of:

userFactory.get(function (user) {
  $scope.user=user;
  if (underscore find if value exsist){
  // do stuff
  }
  else
  {
  //do other stuff
  }
)};

Thoughts?

1 Answer 1

1
var data = {
    "id": 3,
        "data": 'stuff',
        "following": [{
        "id": 213,
            "type": "nope",
    }, {
        "id": 324,
            "type": "nope",
    }, {
        "id": 532,
            "type": "yep",
    }],
};
var result = _.find(data.following, function (item) {
    return item.type === "yep";
});
if(result)
console.log(result);
else
    //do your stuff.

Fiddle

Sign up to request clarification or add additional context in comments.

2 Comments

perfect! What is the difference between _.some and _.find? I actually half figured this out with _.some and it also seems to work fine.
some return boolean and find return list items. Some will be faster.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.