【问题标题】:Lodash filter and omitLodash 过滤和省略
【发布时间】:2016-02-09 12:34:26
【问题描述】:

有没有一种方法可以过滤数组,但使用 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
}];

上面很精彩,但我想省略类型?

【问题讨论】:

  • 浏览器支持?标记为 node.js...

标签: javascript node.js lodash


【解决方案1】:
_.map(_.filter(people,{type : 0}),_.partial(_.omit,_,'type'))

【讨论】:

    【解决方案2】:

    我会为这样的事情使用链式调用。使用filter() 获取您需要的内容,然后使用map() 转换结果。

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      猜你喜欢
      • 2020-04-14
      • 1970-01-01
      • 2016-01-25
      • 2017-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-28
      • 2018-08-24
      相关资源
      最近更新 更多