Lodash过滤器并省略

时间:2016-02-09 12:34:27

标签: javascript node.js lodash

有没有办法可以过滤数组,但是使用lodash省略某些键:值?例如:

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
}];

以上是很棒的,但我想省略类型?

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

我会用链式调用这样的东西。使用filter()获取所需内容,然后map()转换结果。

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

答案 2 :(得分:1)

people_with_type_0可以通过_.map()来获取没有'type'属性的对象:

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

打印:

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