简体   繁体   English

Lodash对象按索引

[英]Lodash object by Index

In lodash, how can I get an object from an array by the index at which it occurs, instead of searching for a key value. 在lodash中,如何通过出现在对象上的索引从数组中获取对象,而不是搜索键值。

var tv = [{id:1},{id:2}]
var data = //Desired result needs to be {id:2}

Let's take for example this collection: 让我们以这个集合为例:

var collection = [{id: 1, name: "Lorem"}, {id: 2, name: "Ipsum"}];

I will talk about two approaches, indexing and not indexing. 我将讨论两种方法,建立索引和不建立索引。

In general, indexing is better if you want to access many of the items, because you loop the collection once. 通常,如果您要访问许多项,则索引会更好,因为您循环了一次集合。 If not, Meeseeks solution with find is the right choice. 如果没有,那么使用find的 Meeseeks解决方案是正确的选择。

Indexing 索引编制

var byId   = _.groupBy(collection, 'id');
var byName = _.groupBy(collection, 'name');

now you can reach each item by it indexed key: 现在您可以通过索引索引访问每个项目:

console.log(byId[2]);      // Object {id: 2, name: "Ipsum"}
console.log(byName.Lorem); // Object {id: 1, name: "Lorem"}

Without indexing 没有索引

var item = _.find(collection, {id: 2});
console.log(item); // Object {id: 2, name: "Ipsum"}

I think what you're looking for is find 我认为您正在寻找的是find

You can give it an object and it will return the matched element or undefined 您可以给它一个对象,它将返回匹配的元素或undefined

Example

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM