NodeJS find object in array by value of a key
Solution 1
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.
Solution 2
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).
Solution 3
classical way is even simpler
try
var output = arr.filter(function(value){ return value.city=="Amsterdam";})
Solution 4
You can use Array.filter
As correctly pointed by @torazaburo, you do not need ternary operator return item[key]?item[key] === value:false
. A simple check return item[key] === value
will do fine.
var arr = [{
city: 'Amsterdam',
title: 'This is Amsterdam!'
}, {
city: 'Berlin',
title: 'This is Berlin!'
}, {
city: 'Budapest',
title: 'This is Budapest!'
}];
Array.prototype.findByValueOfObject = function(key, value) {
return this.filter(function(item) {
return (item[key] === value);
});
}
document.write("<pre>" + JSON.stringify(arr.findByValueOfObject("city", "Amsterdam"), 0, 4) + "</pre>");
Ariel Weinberger
Updated on March 29, 2020Comments
-
Ariel Weinberger about 4 years
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.