Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
189
rated 0 times [  191] [ 2]  / answers: 1 / hits: 128018  / 8 Years ago, mon, march 28, 2016, 12:00:00

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.


More From » arrays

 Answers
14

Using lodash and an arrow function, it should be as simple as;



var picked = lodash.filter(arr, x => x.city === 'Amsterdam');


...or alternately with object notation;



var picked = lodash.filter(arr, { 'city': 'Amsterdam' } );


Note: The above answer used to be based on pickBy, which as @torazaburo points out below was not a good choice for the use case.


[#62788] Thursday, March 24, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
emilee

Total Points: 365
Total Questions: 113
Total Answers: 109

Location: Monaco
Member since Fri, Sep 24, 2021
3 Years ago
;