Inner Filter Not working Properly in Knockout JS

2019-09-06 16:10发布

I have array of static data sized 3.

I am displaying array in right side.

There's one textbox above it for filter. I have taken 2 models for it.

One is field and second is subfield.

one field can have multiple sub fields. I am filtering on field as well as on subfields. It works on fields but shows me some weir output on subfields. there's only one condition that if field's filtered data is added in array then it should not go for subfield, if no match found in field then it can go in subfields and then add data to filtered array.

my fiddle

1条回答
我想做一个坏孩纸
2楼-- · 2019-09-06 16:50

Problem is in condition which you are using for filtering data.As you have more then two subfield so for every match of subfield same data pushed into arr that is the main reason of getting unexpected result.

 self.filteredList = ko.computed(function() {
  var filter = self.filter(),
  arr = [];
if (filter) {
  ko.utils.arrayForEach(self.controlFields(), function(item) {
    if (item.code().match(filter) || item.title().toLowerCase().match(filter.toLowerCase())) {
      arr.push(item);
    }
      ko.utils.arrayForEach(item.subFields(), function(sf) {
        if (sf.title().toLowerCase().match(filter.toLowerCase())) {
          var found = ko.utils.arrayFirst(arr, function(k) {
            return item.title() === k.title() && item.code()===k.code();
          });
          if (!found) {
            arr.push(item);
          }
        }
      });

   });
  } else {
   arr = self.controlFields();
  }
 return arr;
});

Demo

查看更多
登录 后发表回答