devwannabe
devwannabe

Reputation: 3210

Lodash filtering to return object rather than array with 1 length

I'm using this code to filter an array:

var filteredValues = _.filter(arrayOfObjects, function(obj) {
    return obj.id === id;
});

Here's how I'm trying to get the first result:

console.log('id', filteredValues[0].id);

I know how to use chaining but I forgot which lodash function I can use so that the first object found will be assigned to filteredValues.

I can use the code below but it looks too elementary. I want a full lodash solution.

var cleanedfilteredValues = {};
cleanedfilteredValues = filteredValues[0];

Upvotes: 1

Views: 1239

Answers (2)

Adam Boduch
Adam Boduch

Reputation: 11211

When you're using a strict equality operator to compare collection item property values, you can use pass an object to find(), making your code even smaller:

var filteredValues = _.find(arrayOfObjects, { id: id });

Upvotes: 2

devwannabe
devwannabe

Reputation: 3210

With the help of Amadan, this is the code I'm using now

var filteredValues = _.find(arrayOfObjects, function(obj) {
    return obj.id === id;
});

Thanks!

Upvotes: 0

Related Questions