[英]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
})
但它返回真/假而不是整个 object
map
通常用于编辑迭代输入,因此这不是您所需要的。
你可以这样做:
let result = _.filter(items, x => x.type === 'foo')
如果您需要保留相同的密钥,您可以这样做:
let result = _.pickBy(items, x => x.type === 'foo')
如果您不需要重新添加编号,过滤器就足够了。 在这种情况下,您仍然可以通过结合reduce
和filter
轻松逃脱,如下所示:
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.