简体   繁体   中英

Filter an array of nested objects

I have an array of nested objects and I have a user, which searches for a room Here is an array of objects.

在此处输入图片说明

I would like to filter an array as soon as user types something

I tried a lot of functions, but nothing worked for me, here is the last example, which failed

search(val: any) {
// if input is clear - show everything, what we have

    if (val === '') {
      this.roomList = this.roomList;
    } else {
//choose the object (objects) where rName = val

      this.roomList = this.roomList.staticData.rName.filter(function(o) {
        return Object.keys(o).some(function(k) {
          return o[k].toString().toLowerCase().indexOf(val) != -1;
        })
      });
    }
  } 

Could you please help or give me a hint?

You need to apply Array.filter() on roomList instead of staticData propety

this.roomList = this.roomList.filter(function (r) {
    return r.staticData.rName.toLowerCase().indexOf(val.toLowerCase()) != -1
});
this.roomList = this.roomList.staticData.rName

This is a wrong starting point, just look at it. Then, rName is not an array, so you can't invoke .filter on it.

Here's how to do it :

this.roomListFiltered = this.roomList.filter(o => new RegExp(val,"i").test(o.staticData.rName) )

new RegExp(val,"i") performs a case-insensitive match.

Also, store the result of the filter in a different variable, otherwise you will lose your original list as it gets filtered out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM