0

通过使用underscore或者jQuery是否有更好的方法来检查对象数组是否[{id: 1, name: 'some name'}, {id: 2, name: 'other name'}]包含特定的属性值?

这是我的方式:

_.filter([{id: 1}, {id: 2}], 
      function(obj){ return obj.id === 3 }).length === 1; // false

_.filter([{id: 1}, {id: 2}], 
      function(obj){ return obj.id === 2 }).length === 1; // true
4

1 回答 1

0

如果您不需要对象本身,而只是检查它是否在您的列表中:

_.contains(_.pluck([{id: 1}, {id: 2}], 'id'), 1) // => true

文档:_.pluck()_.contains()

于 2012-10-24T12:08:14.207 回答