6

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?

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

2 Comments

I guess u meant return (item.users.some(i => i.surname.toLowerCase().indexOf(value.toLowerCase()) > -1)); This is returning all the users of the object that has one that matches the given surname, I need only the user with that surname. Not sure if the filter is still not correct or if it is and I have to aproach this differently.
Yes. It was my bad. Just updated answer. Now in next snippet it will return list of users which have matching surname.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.