【问题标题】:Filtering with nested arrays使用嵌套数组过滤
【发布时间】:2021-10-29 07:45:38
【问题描述】:

我将在下面给出一个我正在使用敲除编写的示例,但逻辑使用标准js。

<!-- ko foreach: { data: ourWorks, as: 'item' } -->
    <div data-bind="visible: $parent.isVisible(item) "></div>
<!-- /ko -->

tags.name 中只有一个值时的 Js 逻辑

isVisible: function (item) {
    let itemTag = item.tags || [];
    return !!this.chosenTags().length && this.chosenTags().length > 0 ? this.chosenTags().includes(itemTag.name) : item;
},

但如果有多个值,一切都会停止工作。我试图实现嵌套数组的逻辑,但它不起作用,告诉我如何实现它? enter image description here

isVisible: function (item) {
    let itemTag = item.tags || [];
    if (Array.isArray(itemTag)) {
        let tags = this.chosenTags();
        return itemTag.reduce(function(accum, currentVal, currentIndex, tags) {
            return tags ? tags.includes(currentVal) : false;
        }, this);
    }
    return !!this.chosenTags().length && this.chosenTags().length > 0 ? this.chosenTags().includes(itemTag.name) : item;
},

【问题讨论】:

  • 怎么不工作了?你能详细说明一下吗?

标签: javascript filter knockout.js


【解决方案1】:

您可以使用some,如果您希望项目在一个或多个标签名称出现在chosenTags 中时可见。如果所有都应该在chosenTags,你使用every

isVisible: function(item) {
  const itemTags = item.tags || [];
  const chosen = this.chosenTags() || [];

  return itemTags.some(t => chosen.includes(t));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-01
    • 2017-10-08
    • 1970-01-01
    相关资源
    最近更新 更多