Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

_.pluck gives an array of undefined values when it does not find the object

I'm using _.pluck() from lodash to get the value of the keys from an array.

var employees = [
  {
    Name : "abc"  
  },
  {
    Name : "xyz"
  }
]

var res = _.pluck(employees, 'Name'); 

Variable res would contain ['abc,'xyz']

When I do a search for some other field field

var res = _.pluck(employees, 'SomeRandomField');   

Result - [undefined, undefined]

How can I get the above result just as null of undefined instead of an array of undefined values

Plnkr : http://plnkr.co/edit/qtmm6xgdReCuJP5fm1P2?p=preview

like image 639
user1184100 Avatar asked Dec 24 '22 22:12

user1184100


1 Answers

You can use filter and pluck:

var res = _.filter(_.pluck(employees, 'Name'), function(item) {
    return item;
});
like image 121
krynio Avatar answered Dec 28 '22 10:12

krynio