1

I have this collection of objects:

const objects = [
  { id: '11', name: 'ron', surname: 'lesner', group: 'A' },
  { id: '12', name: 'don', surname: 'lesner', group: 'B' },
  { id: '13', name: 'ton', surname: 'lesner', group: 'A' },
]

I need to return the object with matching id using Lodash.

The following code returns undefined:

_.find(object, id, 11);

I'm expecting this result:

{ id: '11', name: 'ron' , surname: 'lesner' , group: 'A' }
GG.
  • 21,083
  • 14
  • 84
  • 130
Aditya
  • 2,358
  • 6
  • 35
  • 61

2 Answers2

5

You need to pass '11' - string representation of the 11 number, because your id is of type string. With Lodash#find

const object = [
     {id: '11', name: 'ron' , surname: 'lesner' , group: 'A'},
     {id: '12', name: 'don' , surname: 'lesner' , group: 'B'},
     {id: '13', name: 'ton' , surname: 'lesner' , group: 'A'}
];

const found = _.find(object , ['id', '13']);

console.log(found);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Also you can use pure Javascript instead of lodash?

const object = [
     {id: '11', name: 'ron' , surname: 'lesner' , group: 'A'},
     {id: '12', name: 'don' , surname: 'lesner' , group: 'B'},
     {id: '13', name: 'ton' , surname: 'lesner' , group: 'A'}
];

const found = object.find(item => item.id === '11');

console.log(found);
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
0

You are not using the lodash find function in accordance with hiw its intended to be used. Please check source code and coments at https://github.com/lodash/lodash/blob/master/find.js

Also for something so trivial it can be argued that you should better use the native array functions if you cannot motivate library use with the need for extreeme performance or other reasons; and also dont call an array Object. It will make your code confusing.

JGoodgive
  • 1,068
  • 10
  • 20