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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With