_.findWhere array-object within array-object property equals something

695 views Asked by At

I have an array like this:

var colors = [
  {
    "name": "red",
    "ids":[
      {
        "id": 1
      }
    ]    
  },
  {
    "name": "blue",
    "ids":[
      {
        "id": 5
      }
    ]    
  }
]

And I essentially want to find the object where the first id within ids is equal to something.

_.findWhere(colors, {
  "ids.0.id": 1
})

Is this the best way to go about it?

var color = _.chain(colors)
.map(function(color){
  color.id = color.ids[0].id
  return color
})
.findWhere({
  "id": 1
})
.value()

console.log(color)
1

There are 1 answers

0
mu is too short On BEST ANSWER

_.findWhere is just a convenience wrapper for _.find so if findWhere doesn't do quite what you need, go straight to find and do it by hand:

var color = _(colors).find(function(color) {
    return color.ids[0].id === 1;
});