stackunderflow
stackunderflow

Reputation: 1714

Lodash filter and omit

Is there a way I can filter on an array, but omit certain key:values using lodash? For example:

var people = [{
    _id: 0,
    name: 'Joe',
    type: 1
}, {
    _id: 1,
    name: 'James',
    type: 2
}, {
    _id: 2,
    name: 'Mary',
    type: 0
}, {
    _id: 3,
    name: 'Clark',
    type: 0
}];

var people_with_type_0 = _.filter(people, { 'type': 0 });

// so people_with_type_0 now contains the following
var people_with_type_0 = [{
    _id: 2,
    name: 'Mary',
    type: 0
}, {
    _id: 3,
    name: 'Clark',
    type: 0
}];

The above is brilliant, but I want to omit the type?

Upvotes: 2

Views: 1208

Answers (3)

Adam Boduch
Adam Boduch

Reputation: 11211

I would use a chained call for something like this. Use filter() to get what you need, then map() to transform the results.

_(people)
  .filter({ type: 0 })
  .map(_.unary(_.partialRight(_.omit, 'type')))
  .value();

Upvotes: 2

Ben
Ben

Reputation: 5074

people_with_type_0 can be pass through _.map() to get the objects without 'type' property:

var array = _.map(people_with_type_0, function(person) {
  return _.omit(person, 'type');
});
console.log(array);

This prints:

[ 
  { _id: 2, name: 'Mary' }, 
  { _id: 3, name: 'Clark' } 
]

Upvotes: 1

Nithin M Thomas
Nithin M Thomas

Reputation: 71

_.map(_.filter(people,{type : 0}),_.partial(_.omit,_,'type'))

Upvotes: 3

Related Questions