0

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

enter image description here

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?

2 Answers 2

3

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

Comments

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.

1 Comment

Because unfortunately that's common place on SO. Make a correct answer and get a few silent downvotes for some reason. Here, that could have been because OP uses ES5, not ES6, but I wouldn't have been told by the downvoter.

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.