admin管理员组文章数量:1291142
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.
var tv = [{id:1},{id:2}] var data = //Desired result needs to be {id:2}
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.
var tv = [{id:1},{id:2}] var data = //Desired result needs to be {id:2}Share Improve this question asked Oct 14, 2015 at 21:19 arkiagoarkiago 331 gold badge1 silver badge5 bronze badges 2
- why do you need lodash if you know the index? – aarosil Commented Oct 14, 2015 at 21:29
-
In ES2015 there is a built-in
Array.prototype.find
for that:const data = tv.find(i => i.id == 2);
– zerkms Commented Oct 22, 2015 at 21:20
2 Answers
Reset to default 7To directly answer your question about retrieving an object from an array using its index in lodash:
Given your array:
var tv = [{id:1},{id:2}];
You can simply use:
var data = tv[1]; // This will give you the desired result: {id:2}
This is a basic JavaScript operation, and you don't really need lodash for this specific task.
However, if you're interested in other ways to fetch items from a collection based on their attributes, I'd like to share a couple of lodash techniques:
- Using find method (similar to the Meeseeks solution):
var collection = [{id: 1, name: "Lorem"}, {id: 2, name: "Ipsum"}];
var item = _.find(collection, {id: 2});
console.log(item); // Outputs: Object {id: 2, name: "Ipsum"}
- Indexing using groupBy (useful when you want to quickly look up objects by attributes multiple times):
var byId = _.groupBy(collection, 'id');
console.log(byId[2]); // Outputs: Object {id: 2, name: "Ipsum"}
But again, if you're simply wanting to get an item from an array based on its position, using the direct array indexing (like tv[1]
) it's the simplest approach.
Hope this clears things up!
I think what you're looking for is find
You can give it an object and it will return the matched element or 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
本文标签: javascriptLodash object by IndexStack Overflow
版权声明:本文标题:javascript - Lodash object by Index - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741527020a2383530.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论