Javascript 将array.filter(x=>;x.n==n)[0]替换为lodash
我经常这样做:Javascript 将array.filter(x=>;x.n==n)[0]替换为lodash,javascript,underscore.js,lodash,Javascript,Underscore.js,Lodash,我经常这样做: var customer = people.filter(function(person) { return person.id === customerId; })[0]; 从语义上讲,我只是简单地说“给我数组中与这个谓词匹配的唯一元素。” 现在我正在使用lodash,最接近的等价物是什么?您可以使用以下功能: var customer = _.findWhere(people, { 'id': customerId }); 或者,您可以使用和的组合: 通常,fin
var customer = people.filter(function(person) {
return person.id === customerId;
})[0];
从语义上讲,我只是简单地说“给我数组中与这个谓词匹配的唯一元素。”
现在我正在使用lodash,最接近的等价物是什么?您可以使用以下功能:
var customer = _.findWhere(people, { 'id': customerId });
或者,您可以使用和的组合:
通常,find(collection,predicate)
函数会在集合
中找到与谓词
匹配的第一个元素。该函数还直接接受where样式的对象参数。函数正在调用find()
欢迎来到堆栈溢出!你能解释一下为什么这个代码能回答这个问题吗?代码唯一的答案是,因为他们不教解决方案。“唯一元素”并不真正准确。它说的是“所有元素中的第一个”
var customer = _.find(people, _.matchesProperty('id', customerId));
var collection [ { id: 1 }, { id: 2 }, { id: 3 } ];
_.find(collection, { id: 2 });
// → { id: 2 }