过滤具有多个条件的对象数组

问题描述 投票:0回答:1

我有一个看起来像这样的对象数组:

const pets = [
    {name: "Dog", tags: "ground, pet, active"},
    {name: "Cat", tags: "ground, pet, relaxed"},
    {name: "Fish", tags: "water, pet, exotic"},
] 

我想根据给定关键字中的

tags
键过滤掉数组:

const search = "ground"
const result = pets.filter((pet) => pet.tags.includes(search)) 

它输出:

[
  { name: 'Dog', tags: 'ground, pet, active' },
  { name: 'Cat', tags: 'ground, pet, relaxed' }
]

如果我想过滤掉

pets
上有多个关键字的
tags
数组,像这样:

const search = ["ground", "active"]

理论上,给定两个关键字应该只能找到

{ name: 'Dog', tags: 'ground, pet, active' }

我有什么想法可以实现这样的目标吗?

javascript arrays json object
1个回答
0
投票

您可以尝试使用

every()

const pets = [
    {name: "Dog", tags: "ground, pet, active"},
    {name: "Cat", tags: "ground, pet, relaxed"},
    {name: "Fish", tags: "water, pet, exotic"},
] 


const search = ["ground", "active"];
const result = pets.filter(pet => search.every(keyword => pet.tags.includes(keyword)));
console.log(result);

© www.soinside.com 2019 - 2024. All rights reserved.