尝试过滤出对象中的值

时间:2018-07-13 02:23:58

标签: javascript arrays 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"] },
    ];

//code below is what I am trying to use to filter
    people.indexOf("Cat")
    }

2 个答案:

答案 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是必需的。根据条件,您可以使用someindexOfincludes