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'
    }   
}];
chovy
  • 72,281
  • 52
  • 227
  • 295

1 Answers1

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>
Tholle
  • 108,070
  • 19
  • 198
  • 189