检查对象数组是否具有具有特定值的键的对象

时间:2012-10-24 12:02:28

标签: javascript jquery underscore.js

使用underscorejQuery是否有更好的方法来检查对象数组[{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

1 个答案:

答案 0 :(得分:0)

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

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

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