根据嵌套属性对数组进行过滤/匹配-多个过滤器

时间:2020-08-12 13:23:49

标签: javascript arrays angular typescript filtering

我有一个简单的选择。该选择返回一个字符串值,例如“ foo”。然后,我将字符串值与列表中的所有条目进行匹配。仅匹配的条目返回。 entry.eventType.description === this.ngxValue; // "foo" === "foo" returns true

例如单选

// this.ngxValue = "foo"

private multiEventTypeFilter(entry) {
    if (this.ngxValue === 'Any') {
        return true;
    } else {
        return entry.eventType.description === this.ngxValue;
    }
}

多选

我现在更改了选择范围以允许多项选择。现在,这将返回一个由所有选定值组成的数组,例如["foo", "bar", "car"]。因此,现在我想返回与该数组中的ANY值匹配的所有条目。 this.ngxValue不再是单个字符串,而是具有多个字符串的数组。以下是需要的...

entry.eventType.description === this.ngxValue; // "foo" === ["foo", "bar", "car"] returns true

任何帮助表示赞赏。

3 个答案:

答案 0 :(得分:1)

尽管Array.prototype.includes()是满足要求的直接方法,但还有另一种选择Array.prototype.some()。 由于您正在寻找其他替代方法,因此请在此处提及,以便日后随时为您提供帮助

下面是示例如何使用Array.prototype.some()

let data = ["foo", "bar", "car"]

console.log(data.some(d => d === "foo"))

根据您的要求,下面是方法

return this.ngxValue.some(val => val === entry.eventType.description);

答案 1 :(得分:0)

return this.ngxValue.indexOf(entry.eventType.description) !== -1;

对不起。我立刻找到了答案。我将在这里发布,但是如果有其他选择,请随时显示。

答案 2 :(得分:0)

您应该使用Array.prototype.includes()

return this.ngxValue.includes(entry.eventType.description);

如果数组中存在该值,它将返回true,否则返回false