首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >过滤MultiCheckbox的对象

问过滤MultiCheckbox的对象
EN

Stack Overflow用户
提问于 2019-04-09 03:26:06
回答 2查看 34关注 0票数 1

我有一个用于筛选对象的多复选框,但我无法处理基于单个条件从复选框中选择的多个选项返回所需对象的条件

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

代码语言:javascript
复制
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。对象中的键代表我拥有的多个选择,它可能会增长。

代码语言:javascript
复制
[ { id: 2, kba: true, email: true },
  { id: 3, kba: true, email: false } ]
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-04-09 03:42:43

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

​

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2019-04-09 19:27:32

因此,据我所知,您希望匹配selectedValue中提供的所有密钥。您可以像这样实现它,例如:

​

代码语言:javascript
复制
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)

​

其仅从具有与selectedValue相同的所有键/值的json数组中选择值。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55580469

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档