luisddr
luisddr

Reputation: 61

How to filter objects that contains object array

could you help with these problem.

I need to filter the items in the array that contains certains activities in their object array. Heres is the code:

let userArray = [{
    name: "alonso",
    age:16,
    hobbies: [{activity:"videogames", id: 1}, {activity:"watch tv", id:2}]
  },
  {
    name: "aaron",
    age:19,
    hobbies: [{activity:"videogames", id:1}, {activity:"soccer", id:8}]
  },
  {
    name: "Luis",
    age:27,
    hobbies: [{activity:"code", id:3}, {activity:"soccer", id:8}]
}]

if "videogames" is passed by string the output expected is:

[{
   name: "alonso",
   age:16,
   hobbies: [{activity:"videogames", id: 1}, {activity:"watch tv", id:2}]
 },
 {
   name: "aaron",
   age:19,
   hobbies: [{activity:"videogames", id:1}, {activity:"soccer", id:8}]
}]

Upvotes: 0

Views: 511

Answers (4)

Yosvel Quintero
Yosvel Quintero

Reputation: 19070

You can use Array.prototype.filter() combined with Array.prototype.some():

const userArray = [{name: 'alonso',age: 16,hobbies: [{ activity: 'videogames', id: 1 },{ activity: 'watch tv', id: 2 },],},{name: 'aaron',age: 19,hobbies: [{ activity: 'videogames', id: 1 },{ activity: 'soccer', id: 8 },],},{name: 'Luis',age: 27,hobbies: [{ activity: 'code', id: 3 },{ activity: 'soccer', id: 8 },],},]

const getUsersByActivity = (array, activity) =>  array.filter(
  user => user.hobbies.some(hobby => activity === hobby.activity)
)

const result = getUsersByActivity(userArray, 'videogames')
console.log(result)

Upvotes: 2

Siva Krishna Madasu
Siva Krishna Madasu

Reputation: 36

userArray.filter(user => {
  if(user.hobbies.some(hobby => hobby.activity == "videogames")){
  return user
  }
  })

Upvotes: 0

GabeM
GabeM

Reputation: 1

using array.filter you could filter out the objects that dont have the trait you are looking for userArray.filter(x => x.hobbies[0].activity === "videogames");

Upvotes: 0

Sathya
Sathya

Reputation: 621

var users = [
{
    name: "aaron",
    age: 19,
    hobbies: [
      { activity: "videogames", id: 1 },
      { activity: "soccer", id: 8 },
    ],
  },
  {
    name: "Luis",
    age: 27,
    hobbies: [
      { activity: "code", id: 3 },
      { activity: "soccer", id: 8 },
    ],
  },
];

function getUsersBasedOnActivity(activity) {
  return users.filter((data) => {
    const hobbies = data.hobbies.map((hobby) => hobby.activity);
    return hobbies.includes(activity);
  });
}

console.log(getUsersBasedOnActivity('videogames'))

Upvotes: 0

Related Questions