简体   繁体   中英

Compare properties to a search string in a multidimensional observable array in knockout.js

I have an observable array in Knockout.js, in which I store a list of persons. The structure of this array looks something like this:

Array
  |--- Person 1
          |--- ID
          |--- Name
          |--- ...
  |--- Person 2
          |--- ID
          |--- Name
          |--- ...
  |--- ...

I have a search bar, which should compare its value to any of the fields of a person. So if I'd type in "000" and that's Person 1's ID, it should be a hit. Same if I'd type in "Person" if that's Person 2's name.

Currently, my code looks something like this:

self.searchValue = ko.observable();
self.throttledValue = ko.computed(self.searchValue).extend({ throttle: 500 });

//Search by value
self.throttledValue.subscribe(function (val) {
    if (val !== ''){ 
        for (var i = 0; i < self.persons().length; i++) {
            var name = self.persons()[i].fullName;
            var id = self.persons()[i].ID;
            //Further search logic here
        }
    }
}, self);

I would like to be able to compare the fields a person has with the search string, like this:

//This code should replace the "further search logic"
if(name.toLowerCase().contains(val.toLowerCase()){
    //It's a hit!
}

But apparently, neither toLowerCase() nor contains() gets recognised, resulting in an error when I try to load my page.

Can anyone help me in the right direction?

Thanks in advance!

toLowerCase() is a string method, it won't work on a number for example.

Try with toString()

if(name.toString().toLowerCase().contains(val.toString().toLowerCase()){
    //It's a hit!
}

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