Search code examples
javascriptlodash

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}

Solution

  • 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!