简体   繁体   中英

How can I return certain objects from object array based on an array inside each object?

For example if I wanted to get a new array of all objects that had a skill of "reading" from the below array, how would I do this?

I tried testResult but just get infinite loop:(

Thanks for all and any help!

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"],
}

]

Expected return:

[{
    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])
    }
})

})

try this

people.filter((e) => e.skills.indexOf('reading') > -1)
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]); 
      }
   }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM