Node.js lodash find() find object by attribute

Description

Node.js lodash find() find object by attribute


var _ = require('lodash');

var people = [/*from   ww w . j a v  a  2  s .c  om*/
  { id: 1, name: "Jim", age: 20, gender: 'm', enabled: true },
  { id: 1, name: "Jim", age: 20, gender: 'm', enabled: false },  
  { id: 2, name: "Bob", age: 34, gender: 'm', enabled: true },
  { id: 3, name: "Steve", age: 30, gender: 'm', enabled: true },
  { id: 4, name: "Nancy", age: 42, gender: 'f', enabled: true },
  { id: 5, name: "Frank", age: 30, gender: 'm', enabled: true },
  { id: 6, name: "Larry", age: 68, gender: 'm', enabled: true }
];

var nancy = _.find(people, { name: 'Nancy'});
console.log(nancy);

var jim = _.find(people, { name: 'Jim'} );
console.log(jim);

jim = _.findLast(people, { name: 'Jim'});
console.log(jim);

More example

//Returns the matched element, else undefined.
var lodash = require('lodash');
var users = [//  ww w. j  a  v  a  2  s.co m
  { 'user': 'barney',  'age': 36, 'active': true },
  { 'user': 'fred',    'age': 40, 'active': false },
  { 'user': 'pebbles', 'age': 1,  'active': true }
];
console.log(lodash.find(users, function(chr) {
  return chr.age < 40;
}))



PreviousNext

Related