Reputation: 473
I'm trying to filter a list with many objects with the following structure:
{
"element1":{
"code":"12345",
"location":"Location"
},
"users":[
{
"id":1,
"name":"Name 1",
"surname":"Surname 1",
},
{
"id":2,
"name":"Name 2",
"surname":"Surname 2",
}
]
}
Right now I am filtering it by the first element like this:
filterList(value) {
if (value&& value.trim() != '') {
myList = myList .filter((item) => {
return (item.element1.location.toLowerCase().indexOf(value.toLowerCase()) > -1);
})
}
}
I've been trying to adapt this to filter them by the users attribute which is a list of objects and inside that by the surname what do I have to change?
Upvotes: 6
Views: 2385
Reputation: 12619
You can filter by users' surname by replacing filter condition as below. This will return parent object which have one that matches the given surname.
return (item.users.some(i => i.surname.toLowerCase().indexOf(value.toLowerCase()) > -1));
If you want the list of users then your filter would be like as below.
var usersList = [];
myList.forEach(i => Array.prototype.push.apply(usersList, i.users));
usersList = usersList.filter(i => i.surname.toLowerCase().indexOf(value.toLowerCase()) > -1);
Upvotes: 3