1

I'm trying to use underscore to find an object in the array which has a child with a certain condition. lets say this is my array:

"array": [
  {
     "user": {
        "profileIcon": 913,
        "id": 62019870
     },
     "count": 1
  },
  {
     "user": {
        "profileIcon": 770,
        "id": 32558522
     },
     "count": 2
  }
]

Now I want to only return an object that has user.id : 62019870. This is the code I have so far but it returns an empty array:

 var arr = _.filter(array, function(obj) {
                return _.findWhere(obj.user, {id: 62019870});
            });

1 Answer 1

3

findWhere function works on the array, not on the object. For your case, you can simply do

console.log(_.filter(array, function(obj) {
  return obj.user.id === 62019870;
}));
// [ { user: { profileIcon: 913, id: 62019870 }, count: 1 } ]

If your environment supports, native Array.prototype.filter then you can do the same without underscore, like this

array.filter(function(obj) {
  return obj.user.id === 62019870;
});

If your environment supports ECMA Script 2015's Arrow functions, then you can write the same, more succinctly, like this

array.filter(obj => obj.user.id === 62019870);
Sign up to request clarification or add additional context in comments.

2 Comments

I will prefer @alexreardon way, if I don't need to worry about IE8 it's native filter .
@alexreardon Thanks, included that suggestion also in the answer.

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.