gpt4 book ai didi

javascript - 通过对象过滤 MultiCheckbox

转载 作者:行者123 更新时间:2023-11-30 19:39:18 24 4
gpt4 key购买 nike

我有一个用于过滤对象的多复选框,我无法处理根据从复选框中选择的多个选项的单个条件返回必要对象的条件

我已经使用 && 运算符编写了条件,它会查找与指定条件完全匹配的内容

let json = [{  
"id": 1,
"kba": false,
"email": true
},
{
"id": 2,
"kba": true,
"email": true
},{
"id": 3,
"kba": true,
"email": false
}]


function integrationFilter(selectedValue){
return truthy = json.filter(j => {
return j.kba === selectedValue.kba && j.email === selectedValue.email
})
}

let selectedValue1 = {"email": false}
let t2 = {"kba": true}
let t3 = {"email": true, "kba": false}


let op = integrationFilter(t2)
console.log(op)

根据我的上述逻辑,我得到了一个空数组。但我想得到结果,因为我将 kba 传递为 true。它们在对象中的键代表我拥有的多种选择,并且它可能会增长。

[ { id: 2, kba: true, email: true },
{ id: 3, kba: true, email: false } ]

最佳答案

您正在检查 &&,它期望两个语句都为 true。我修改了你的过滤器函数来处理你的场景。

let json = [{
"id": 1,
"kba": false,
"email": true
},
{
"id": 2,
"kba": true,
"email": true
}, {
"id": 3,
"kba": true,
"email": false
}
]


function integrationFilter(selectedValue) {
return json.filter(j => {
return Object.entries(selectedValue).every(([key, value]) => {
return j[key] === value;
});
});
}

let t1 = {
"email": false
}
let t2 = {
"kba": true
}
let t3 = {
"email": true,
"kba": false
}


console.log('t1:', integrationFilter(t1));
console.log('t2:', integrationFilter(t2));
console.log('t3:', integrationFilter(t3));

关于javascript - 通过对象过滤 MultiCheckbox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55580469/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com