【问题标题】:Lodash filter by object of objectLodash 按对象过滤
【发布时间】:2022-01-18 00:02:52
【问题描述】:

如何按类型过滤项目?

const items = {
        'someHash0': {
          type: 'foo',
          name: 'a'
        },
        'someHash1': {
          type: 'foo',
          name: 'b'
        },
        'someHash2': {
          type: 'foo',
          name: 'c'
        },
        'someHash3': {
          type: 'baz',
          name: 'd'
        },
      };

我想按 type=foo 过滤并得到结果:

const items = {
        'someHash0': {
          type: 'foo',
          name: 'a'
        },
        'someHash1': {
          type: 'foo',
          name: 'b'
        },
        'someHash2': {
          type: 'foo',
          name: 'c'
        }
      };

我试过了

 return _.mapValues(pairs, function (item) {
     return (item.type === 'foo') ?? item
})

但它返回真/假而不是整个对象

【问题讨论】:

  • 这是为了简化示例,在我实际使用的现金中,它是哈希值。 ps:为清楚起见进行了编辑

标签: javascript lodash


【解决方案1】:

map 通常用于编辑迭代输入,因此不是您需要的。

你可以这样做:

let result = _.filter(items, x => x.type === 'foo')

如果您需要保留相同的密钥,您可以这样做:

let result = _.pickBy(items, x => x.type === 'foo')

【讨论】:

  • 非常感谢,正在寻找 _.pickBy()
【解决方案2】:

如果您不需要重新添加编号,过滤器就足够了。在这种情况下,您仍然可以通过组合reducefilter 轻松逃脱,如下所示:

const items = {
  '0': {
    type: 'foo',
    name: 'a'
  },
  '1': {
    type: 'foo',
    name: 'b'
  },
  '2': {
    type: 'foo',
    name: 'c'
  },
  '3': {
    type: 'baz',
    name: 'd'
  },
};

const mapped = _.reduce(_.filter(items, (item) => item.type === 'foo'), (acc, item, index) => {
  acc[index] = item
  return acc
}, {})

console.log(mapped)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>

【讨论】:

    猜你喜欢
    • 2016-05-24
    • 1970-01-01
    • 2016-03-23
    • 1970-01-01
    • 1970-01-01
    • 2016-11-17
    • 2018-08-22
    • 2023-01-25
    • 1970-01-01
    相关资源
    最近更新 更多