0
在lodash中,我怎样才能从数组中找到一个对象,而不是搜索关键字值。按索引排列的对象
var tv = [{id:1},{id:2}] var data = //Desired result needs to be {id:2}
在lodash中,我怎样才能从数组中找到一个对象,而不是搜索关键字值。按索引排列的对象
var tv = [{id:1},{id:2}] var data = //Desired result needs to be {id:2}
让我们例如这个系列:
var collection = [{id: 1, name: "Lorem"}, {id: 2, name: "Ipsum"}];
我会谈论两种方法,索引和不索引。
一般来说,如果您想访问许多项目,索引编制会更好,因为您只需循环一次该集合。如果没有,Meeseeks解决方案找到是正确的选择。
var byId = _.groupBy(collection, 'id');
var byName = _.groupBy(collection, 'name');
现在
通过它索引键就可以到达的每个项目:
console.log(byId[2]); // Object {id: 2, name: "Ipsum"}
console.log(byName.Lorem); // Object {id: 1, name: "Lorem"}
var item = _.find(collection, {id: 2});
console.log(item); // Object {id: 2, name: "Ipsum"}
我想你要寻找的是find
你可以给它一个对象,它会返回匹配的元素或undefined
例
var arr = [ { id: 1, name: "Hello" }, { id: 2, name: "World" } ];
var data = _.find(arr, { id: 1 }); // => Object {id: 1, name: "Hello"}
var data = _.find(arr, { id: 3 }); // => undefined
为什么你需要lodash如果你知道索引? – aarosil
在ES2015中有一个内置的['Array.prototype.find'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find): 'const data = tv.find(i => i.id == 2);' – zerkms