NodeJS finds an object in an array by key value

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

Array:

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

I tried to do something similar with help lodash, but did not succeed.

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

and returns an empty object.

Any idea on how I can do this in a lodash way (if possible)? I can do this in a classic way by creating a new array, going through all the objects and clicking on those that match my criteria for this new array. But is there a way to do this with lodash?

This is not a duplicate.

+4
source share
4 answers

Using lodash and the arrow function, it should be as simple as:

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

... ;

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

. pickBy, , @torazaburo , .

+9

Array.prototype.find() javascript:

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

, ( NodeJS).

+21

var output = arr.filter(function(value){ return value.city=="Amsterdam";})
+2

Array.filter

@torazaburo, return item[key]?item[key] === value:false. return item[key] === value .

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>");
Hide result
+1

All Articles