有人可以协助我吗?我正在尝试使用Cat过滤所有记录。但是我的方法不起作用。请参见下面的代码
const people = [
{ name: "Kerrie", skills: ["Cat", "Rat", "Orange"] },
{ name: "Mario", skills: ["Mouse", "Dog"] },
{ name: "Jacquline", skills: ["Cat", "Pineapple"] },
{ name: "Kathy", skills: ["Cat", "Java"] },
{ name: "Anna", skills: ["Cat", "Dog"] },
{ name: "Matt", skills: ["Apple", "Dog"] },
{ name: "Matt", skills: ["Apple", "Mango", "Rat"] },
];
//code below is what I am trying to use to filter
people.indexOf("Cat")
}
答案 0 :(得分:0)
简单。您想为.filter
数组中的技能属性包括"Cat"
的元素:
const people = [
{ name: "Kerrie", skills: ["Cat", "Rat", "Orange"] },
{ name: "Mario", skills: ["Mouse", "Dog"] },
{ name: "Jacquline", skills: ["Cat", "Pineapple"] },
{ name: "Kathy", skills: ["Cat", "Java"] },
{ name: "Anna", skills: ["Cat", "Dog"] },
{ name: "Matt", skills: ["Apple", "Dog"] },
{ name: "Matt", skills: ["Apple", "Mango", "Rat"] },
];
let result = people.filter( elem => elem.skills.includes("Cat") );
console.log(result)
答案 1 :(得分:0)
const people = [
{ name: "Kerrie", skills: ["Cat", "Rat", "Orange"] },
{ name: "Mario", skills: ["Mouse", "Dog"] },
{ name: "Jacquline", skills: ["Cat", "Pineapple"] },
{ name: "Kathy", skills: ["Cat", "Java"] },
{ name: "Anna", skills: ["Cat", "Dog"] },
{ name: "Matt", skills: ["Apple", "Dog"] },
{ name: "Matt", skills: ["Apple", "Mango", "Rat"] },
];
let answer = people.filter(x=>x.skills.some(x=> x === "Cat"));
console.log(answer)
因此,要进行过滤,Array#filter是必需的。根据条件,您可以使用some
或indexOf
或includes