在淘汰赛中过滤嵌套数组

时间:2016-02-25 05:57:25

标签: knockout.js

我有需要根据用户输入过滤数组的场景。下面是我的json。

[
  {
    "storename": "store 1",
    "license": "12314",
    "books": [
      "abc",
      "def",
      "cdf"
    ]
  },
  {
    "storename": "store 2",
    "license": "12344",
    "books": [
      "dfd",
      "eww"
    ]
  },
  {
    "storename": "store 3",
    "license": "12344",
    "books": [

    ]
  }
]

我想过滤嵌套数组的项目,应始终返回商店名称和许可证,但是会根据用户输入返回books数组。

我尝试使用ko.utils.arrayFilter,但没有运气。例如,如果用户搜索book abc输出应为。

[
  {
    "storename": "store 1",
    "license": "12314",
    "books": [
      "abc"
    ]
  },
  {
    "storename": "store 2",
    "license": "12344",
    "books": [
    ]
  },
  {
    "storename": "store 3",
    "license": "12344",
    "books": [

    ]
  }
]

1 个答案:

答案 0 :(得分:1)

尽管原始阵列不包含任何淘汰赛:

var data = [
  {
    "storename": "store 1",
    "license": "12314",
    "books": [
      "abc",
      "def",
      "cdf"
    ]
  },
  {
    "storename": "store 2",
    "license": "12344",
    "books": [
      "dfd",
      "eww"
    ]
  },
  {
    "storename": "store 3",
    "license": "12344",
    "books": [

    ]
  }
];

function ViewModel(data) {
  var self = this;
  self.filter = ko.observable("a");
  self.items = ko.computed(function() {
    return data.filter(function(item) {
      return ko.unwrap(item.books).some(function(book) { return book.indexOf(self.filter()) !== -1; });
    });
  });
}

ko.applyBindings(new ViewModel(data));
.store-item {
  border: 1px solid gray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<span>Filter text: </span><input data-bind="value: filter, valueUpdate: 'keyup'" />
<div>Search results:</div>
<!-- ko foreach: items -->
<div class="store-item">
<span>Store name: </span><span data-bind="text: storename"></span>
<br>
<span>License: </span><span data-bind="text: license"></span>
<br>
<!-- ko foreach: books -->
<span>Book: </span><span data-bind="text: $data"></span>
<br>
<!-- /ko -->
</div>  
<!-- /ko -->