var namePerson = [{ name: "Andi", age: "25", hobbies: ["Soccer", "Badminton"],},
{ name: "Robert", age: "25", hobbies: ["Read", "Swim", "Soccer"],},
{ name: "Julia", age: "28", hobbies: ["Music", "Swim"],},];
var arrayPersonFilter = namePerson.filter(function (item) { return item.age == 25;});
var arrayPersonFilter2 = namePerson.filter(function (item) { return item.hobbies == Music";
});
console.log("==========Age============");
console.log(arrayPersonFilter);
console.log("==========Hobbies============");
console.log(arrayPersonFilter2);
I can't filter hobbies with the same method that age filterthis is a result
CodePudding user response:
To filter from an array you can use array.includes. Also, you can use arrow functions here to make it slimmer, easier to read and best practices.
let arrayPersonFilter = namePerson.filter(item => item.age == 25);
let arrayPersonFilter2 = namePerson.filter(item => item.hobbies.includes("Music"));
let namePerson = [{
name: "Andi",
age: "25",
hobbies: ["Soccer", "Badminton"],
},
{
name: "Robert",
age: "25",
hobbies: ["Read", "Swim", "Soccer"],
},
{
name: "Julia",
age: "28",
hobbies: ["Music", "Swim"],
},
];
let arrayPersonFilter = namePerson.filter(item => item.age == 25);
let arrayPersonFilter2 = namePerson.filter(item => item.hobbies.includes("Music"));
console.log("==========Age============");
console.log(arrayPersonFilter);
console.log("==========Hobbies============");
console.log(arrayPersonFilter2);
CodePudding user response:
age is a value, hobbies is an array, so you need to do some check on the items in the array, maybe something like this. Not sure if includes is the right function, but hope it makes sense.
var arrayPersonFilter2 = namePerson.filter(function (item) { return
item.hobbies.includes("Music");
});