javascript - 根据来自另一个对象数组的多个值过滤对象数组
问题描述
我有一个对象数组,
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',
}
]
现在 arr 显示在带有多个选择选项的下拉列表中,并且对象中键值的值显示给用户,即利润 1、cat1 等。因此,如果用户选择profit1
and cat1
,那么我需要过滤数组c
,这样,输出看起来像这样。
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.
解决方案
-您istruecat
仅根据arr
. 您应该使用 reduce 来累积值:
let result = c.filter(e => arr.reduce((acc, element) => acc && e[element.type] === element.value, true))
推荐阅读
- r - 调试模式后变量未出现在 RStudio 全局环境中
- javascript - 通过 javascript 显示的 SVG 绘图不显示
- c# - 当你获得一定的分数时,如何在 C# 中添加新的玩家生活?
- c# - 如何获取在不同 AppDomain 中加载的 ac# 程序集的内存基地址
- php - Moodle 错误:检测到数据库驱动程序问题
- kuzzle - Kuzzle:执行此操作的权限不足
- javascript - 过滤低值余额并隐藏空复选框
- geometry - 不能从空值创建匀称的几何图形
- python - 从 py 文件中使用 scrapy(不在命令行中)
- css - 如何将多个内联样式作为道具应用到组件?