Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

var tv = [{id:1},{id:2}]
var data = //Desired result needs to be {id:2}
like image 372
arkiago Avatar asked Feb 20 '26 17:02

arkiago


2 Answers

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!

like image 193
Ezequias Dinella Avatar answered Feb 23 '26 06:02

Ezequias Dinella


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
like image 33
Mr. Meeseeks Avatar answered Feb 23 '26 07:02

Mr. Meeseeks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!