Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter array with nested objects Angular 5

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?

like image 588
Ayane Avatar asked Jun 24 '18 14:06

Ayane


1 Answers

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);
like image 116
Karan Avatar answered Oct 29 '22 09:10

Karan