我有一个用于过滤对象的多复选框,并且我无法处理根据一个条件从复选框中选择的多个选项返回必要对象的条件
我已经使用&&运算符编写了条件,它会查找与指定条件完全匹配的
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 } ]
答案 0 :(得分:1)
您正在使用&&
进行检查,该期望两个语句都为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));
答案 1 :(得分:0)
因此,据我了解,您希望匹配selectedValue
中提供的所有键。例如,您可以这样实现:
let json = [{
"id": 1,
"kba": false,
"email": true
},
{
"id": 2,
"kba": true,
"email": true
},{
"id": 3,
"kba": true,
"email": false
}]
function integrationFilter(selectedValue){
const keysToValidate = Object.keys(selectedValue);
return json.filter(j => {
for (let key in selectedValue)
if (j[key] !== selectedValue[key])
return false;
return true;
})
}
let selectedValue1 = {"email": false}
let t2 = {"kba": true}
let t3 = {"email": true, "kba": false}
let op = integrationFilter(t2)
console.log(op)
仅从json
数组中选择所有键/值都与selectedValue
相同的值。