2

I have an array of objects which have a property .names which is another object.

I am using lodash...is there a helper method to get the user whose yahoo name is foo in the following example?

const users = [{
    names: {
        yahoo: 'foo',
        gmail: 'bar'
    }
}, {
    names: {
        yahoo: 'foo2',
        gmail: 'bar2'
    }   
}];
3
  • Array#find should do this... Commented Sep 14, 2016 at 5:46
  • can you provide an example of Array#find? Commented Sep 15, 2016 at 2:25
  • Provided link has few examples... Commented Sep 15, 2016 at 2:27

1 Answer 1

3

You can use find with a custom predicate:

var result = _.find(users, function(user) {
  return user.names.yahoo === 'foo';
});

users = [{
  names: {
   yahoo: 'foo',
   gmail: 'bar'
  }
}, {
  names: {
   yahoo: 'foo2',
   gmail: 'bar2'
  }   
}];

var result = _.find(users, function(user) {
  return user.names.yahoo === 'foo';
});

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

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

1 Comment

you can also do it shorthand _.find(users, { names: { yahoo: 'foo' } })

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.