首页 > 解决方案 > 如何过滤数组以仅返回白名单中包含至少一个嵌套属性的项目?

问题描述

我实际上要做的是过滤我的 GitHub 问题(通过 REST API),以仅显示包含与我的特定白名单匹配的标签的问题。

const issues = [
    {
        issue_name: "My issue",
        labels: [{ name: "Foo" }, { name: "Bar" }, { name: "Baz" }],
    },
    {
        issue_name: "My issue",
        labels: [{ name: "Red" }, { name: "Green" }, { name: "Blue" }],
    },
];

const whitelist = ['Baz'];

// How to filter issues to only an issue that has at least one label contained in the whitelist?

const filtered = issues.filter(issue => issue.labels.forEach(label => whitelist.indexOf(label) > - 1);

// ?? not sure of something like this would work?

我被卡住了,因为a)标签名称是嵌套的,b)有多个,所以我不知道如何迭代可能的标签名称以返回过滤的问题列表。

标签: javascriptarraysfilter

解决方案


最好使用 JS find 来做到这一点:

const filtered = issues.filter(i=> i.labels.find(l => whitelist.find(w => w == l.name)))

推荐阅读