36

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.

6
  • @JoachimIsaksson Why can't you post an answer? It's exactly what I was looking for! I would mark it as answered Commented Mar 28, 2016 at 10:07
  • @Rajesh because of the uniform principle. I use lodash for all object/array manipulations in my Node application and if possible - I would like to use it where possible. Commented Mar 28, 2016 at 10:08
  • 1
    Yes, none of the 10M questions on SO has ever asked how to find the element of an array of objects based on one of the objects' properties. If you don't like the question this is marked as a duplicate of, try stackoverflow.com/questions/7364150/…. Commented Mar 28, 2016 at 10:22
  • @torazaburo For something to be a duplicate of something else, it has to be identical. None of these questions involve any lodash. I was asking specifically for lodash, therefore this is not a duplicate. Commented Mar 28, 2016 at 10:29
  • 1
    The link I gave contains an answer for underscore, which is pretty much identical to lodash, and a comment on that answer specifically references lodash. Instead of quibbling over the definition of duplicate, I suggest you simply browse through the lodash docs, and you will quickly find the answer to your question. For instance, you would soon find the _.find routine. You would also find an example which matches your use case exactly, which is _.find(users, _.matchesProperty('city', 'Amsterdam'));. It's always been a mystery to me why people think SO is a "read the docs for me" service. Commented Mar 28, 2016 at 10:43

4 Answers 4

104

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Careful which version of node, it does not work in all versions.
Not working in 0.10.25, but should work in recent Node versions.
17

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.

1 Comment

pickBy is not what he wants here. pickBy picks certain properties matching the predicate. It will create an object instead of a filtered array.
8

classical way is even simpler

try

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

2 Comments

return value.city == 'Amsterdam'* :) Thanks!
Well, to be picky, he said get an object and you are returning a list of objects.
2

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>");

4 Comments

I think it should be just return item[key] === value;.
@torazaburo yup you are correct. Have habit of checking. Will update my answer.
How can i get only an object instead of array?
@shiva if its unique or you expect to get first occurrence, you can use Array.find instead. It will return Object in matched or null if no match

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.