1467
1467

Reputation: 1

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

})

Upvotes: 0

Views: 23

Answers (3)

Piyush Mahapatra
Piyush Mahapatra

Reputation: 223

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

Upvotes: 0

user6057915
user6057915

Reputation:

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]); 
      }
   }

}

Upvotes: 0

Manish
Manish

Reputation: 77

try this

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

Upvotes: 1

Related Questions