[英]Filter array of objects based on multiple values from another array of objects
我有一个对象数组,
c = [
{
name: 'abc',
category: 'cat1',
profitc: 'profit1',
costc: 'cost1'
},
{
name: 'xyz',
category: '',
profitc: 'profit1',
costc: ''
},
{
name: 'pqr',
category: 'cat1',
profitc: 'profit1',
costc: ''
}
]
现在我想根据另一个对象数组过滤数组,第二个对象数组是,
arr = [
{
type:'profitc'
value: 'profit1',
},
{
type:'category'
value: 'cat1',
}
]
Now the arr is shown in dropdown with multiple select option and the value of key value in the object is shown to the user ie profit1, cat1, etc. So if a user selects profit1
and cat1
, then I need to filter the array c
such也就是说,output 看起来像这样。
c = [
{
name: 'abc',
category: 'cat1',
profitc: 'profit1',
costc: 'cost1'
},
{
name: 'pqr',
category: 'cat1',
profitc: 'profit1',
costc: ''
}
]
我试着这样做。
let result = c.filter(e => {
let istruecat = true
//arr is chosen value from user.
arr.forEach(element => {
istruecat = e[element.type] == element.value;
})
return istruecat;
})
但是当我这样做时,我会从c
数组中获取所有对象。 我在这里做错了什么? 有没有办法使用 lodash.
-您仅根据arr
中的最后一个条目计算istruecat
。 您应该使用 reduce 来累积值:
let result = c.filter(e => arr.reduce((acc, element) => acc && e[element.type] === element.value, true))
您可以通过使用数据对象检查所有给定的键/值对来过滤数组。
var data = [{ name: 'abc', category: 'cat1', profitc: 'profit1', costc: 'cost1' }, { name: 'xyz', category: '', profitc: 'profit1', costc: '' }, { name: 'pqr', category: 'cat1', profitc: 'profit1', costc: '' }], filters = [{ type: 'profitc', value: 'profit1', }, { type: 'category', value: 'cat1' }], result = data.filter(o => filters.every(({ type, value }) => o[type] === value)); console.log(result);
.as-console-wrapper { max-height: 100%;important: top; 0; }
这是基于过滤器数组arr
的给定值减少列表c
的实现。 请注意, output 是基于c
中的初始内容的新列表。
result = arr.reduce((acc, curr) => {
acc = acc.filter(item => {
return item[curr.type] === curr.value;
});
return acc;
}, c);
或者一个递归和imo可读的解决方案:
function myFilter(c, [first, ...rest]) {
if (first) {
const {type, value} = first;
// Recursively call myFilter with one filter removed
return myFilter(c, rest)
.filter(x => x[type] === value);
} else {
// Nothing left to filter
return c;
}
}
myFilter(c, arr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.