Michael
Michael

Reputation: 13614

Lodash function does not work properly

I have array of object:

var arr = [{id:1, name:Michael},
    {Id:2, name:"Mix"},
    {Id:3, name:"Mark"},
    {Id:4, name:"Marta"},
    {Id:5, name:"Anna"}];

var desiredId = 3;

I try to get object from object array with help of lodash library like that:

var result = _.find(arr, 'Id', desiredId);

But I always get object with id = 1(i.e {id:1, name:Michael}).

Any idea why I don't get the expected object (where Id = 3).

Upvotes: 1

Views: 2558

Answers (1)

ryeballar
ryeballar

Reputation: 30098

If you check the find() lodash documentation, there should be an example where you can use a matches() shorthand. You will notice that this shorthand is a common occurence when querying from collections.

Example:

var arr = [
    {Id:1, name:"Michael"},
    {Id:2, name:"Mix"},
    {Id:3, name:"Mark"},
    {Id:4, name:"Marta"},
    {Id:5, name:"Anna"}
];

var desiredId = 3;
var result = _.find(arr, { Id: desiredId });

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.12.0/lodash.js"></script>

Upvotes: 2

Related Questions