如何根据每个对象内的数组从对象数组中返回某些对象?

时间:2021-04-16 15:46:58

标签: javascript loops iterator

例如,如果我想从下面的数组中获取具有“读取”技能的所有对象的新数组,我该怎么做?

我试过 testResult 但只是无限循环 :(

感谢大家的帮助!

const people = [{
    name: "Jon",
    skills: ["reading", "acting", "drinking"],
},
{
    name: "Tim",
    skills: ["rowing", "hockey", "reading"],
},
{
    name: "Lucy",
    skills: ["business", "learning", "hockey"],
},
{
    name: "Michelle",
    skills: ["running", "business", "sleeping"],
},
{
    name: "Michael",
    skills: ["making friends", "surfing"],
}

]

预期回报:

[{
    name: "Jon",
    skills: ["reading", "acting", "drinking"],
},
{
    name: "Tim",
    skills: ["rowing", "hockey", "reading"],
}]

const testResult = testArray.map((obj) => {
obj.skills.map((skill) => {
    if (skill === "reading") {
        setPeople([...people, obj])
    }
})

})

3 个答案:

答案 0 :(得分:1)

试试这个

people.filter((e) => e.skills.indexOf('reading') > -1)

答案 1 :(得分:0)

var people_new = []; 

for(var i = 0; i < people.length; i++) 
{

   var skills = people[i].skills; 
   
   for(var s = 0; s < skills.length; s++) 
   {
      if( skills[s] == "reading" ) 
      {
         people_new.push(people[i]); 
      }
   }

}

答案 2 :(得分:0)

let filterd = []
for(item of people){
    if(item.skills.includes('reading')){
        filterd.push(item)
    }
}
console.log(filtered) // array of objs