Lodash 按对象过滤

Lodash filter by object of object

如何按类型筛选项目?

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
})

但它 returns true/false 而不是整个对象

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

你可以这样做:

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

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

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

如果您不需要重新添加编号,一个过滤器就足够了。在那种情况下,您仍然可以通过组合 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>