简体   繁体   English

Lodash过滤器由object的object

[英]Lodash filter by object of object

How to filter items by type?如何按类型过滤项目?

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

I want to filter by type=foo and get that result:我想按 type=foo 过滤并得到结果:

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

I tryied with我试过了

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

but it returns true/false instead of the whole object但它返回真/假而不是整个 object

map in general is for editing iterated inputs, so it's not what you need. map通常用于编辑迭代输入,因此这不是您所需要的。

You can do like this:你可以这样做:

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

If you need to keep the same keys you could do it like this:如果您需要保留相同的密钥,您可以这样做:

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

A filter would be enough if you didn't need to re-add the numbering.如果您不需要重新添加编号,过滤器就足够了。 In that case, you can still get away rather easily by combining reduce and filter , as follow:在这种情况下,您仍然可以通过结合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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM