【发布时间】:2020-09-30 20:16:49
【问题描述】:
我有这个对象数组
const bnb = [
{
"id": "id1",
"img": ["tres", "dos", "uno"],
"title": "one",
"city": "texas",
"saved": false,
"tags": ["bath"]
},
{
"id": "id2",
"img": ["quatro", "uno", "tres"],
"title": "two",
"city": "denver",
"saved": false,
"tags": ["wc"]
},
{
"id": "id3",
"img": ["uno", "dos", "tres"],
"title": "three",
"city": "vancouver",
"saved": false,
"tags": ["wc", "bath"]
},
{
"id": "id4",
"img": ["dos", "uno", "tres"],
"title": "four",
"city": "berlin",
"saved": false,
"tags": ["bath", "parking"]
},
{
"id": "id5",
"img": ["tres", "uno", "quatro"],
"title": "five",
"city": "paris",
"saved": false,
"tags": ["loft", "parking", "kitchen"]
},
{
"id": "id6",
"img": ["quatro", "uno", "tres"],
"title": "six",
"city": "barcelona",
"saved": false,
"tags": ["bath", "wc"]
},
{
"id": "id7",
"img": ["uno", "tres", "quatro"],
"title": "seven",
"city": "seul",
"saved": false,
"tags": ["parking", "wc", "kitchen"]
}
]
我想按标签过滤列表。例如,当我单击复选框时,列表应该根据所选值给我过滤数组。当我单击复选框时,它会创建具有单击值的新数组,例如 let checked = ["parking", "kitchen"] 匹配 bnb
<input type="checkbox" value="parking">Parking<br>
<input type="checkbox" value="kitchen">Kitchen<br>
...
我知道我可以像这样使用过滤器功能,但它不过滤数组。
let bnblist = bnb.filter(o => o.tags.includes(checked);
另一件事是过滤应该减去数组,例如,如果我选择了["parking", "kitchen"],它应该返回 id5 和 id7。基本上它类似于 && 运算符,但它需要选择两个值,并且有多个复选框,我不知道要选择多少用户。
let bnblist = bnb.filter(o => o.tags === "parking" && "kitchen");
【问题讨论】:
标签: javascript arrays filter chaining