Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS find object in array by value of a key [duplicate]

I am trying to get an object in an array by the value of one of its keys.

The array:

var arr = [         {             city: 'Amsterdam',             title: 'This is Amsterdam!'         },         {             city: 'Berlin',             title: 'This is Berlin!'         },         {             city: 'Budapest',             title: 'This is Budapest!'         } ]; 

I tried doing something like this with lodash but no success.

var picked = lodash.pickBy(arr, lodash.isEqual('Amsterdam'); 

and it returns an empty object.

Any idea on how I can do this the lodash way (if it's even possible)? I can do it the classic way, creating a new array, looping through all objects and pushing the ones matching my criteria to that new array. But is there a way to do it with lodash?

This is NOT a duplicate.

like image 819
Ariel Weinberger Avatar asked Mar 28 '16 09:03

Ariel Weinberger


1 Answers

You can use Array.prototype.find() with pure javascript:

var picked = arr.find(o => o.city === 'Amsterdam'); 

It is currently not compatible with all browsers, you need to check it in your environment (but it should work in NodeJS).

like image 127
madox2 Avatar answered Sep 19 '22 18:09

madox2