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
Add a ment  | 

2 Answers 2

Reset to default 7

To 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:

  1. 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"}
  1. 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