Home > Net >  How to filter objects that contains object array
How to filter objects that contains object array

Time:05-03

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

CodePudding user response:

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'))

CodePudding user response:

You can use Array.prototype.filter() 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)

  • Related