You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何过滤respProducts数组:移除存在于currentTemplates中的元素

问题:过滤数组中匹配对象键名的元素

现有两个数据结构:respProducts数组与currentTemplates对象。需要过滤respProducts,移除其中node.title与currentTemplates键名完全匹配的元素,同时保留原数组的结构。但当前尝试的过滤代码返回空数组,求正确实现方式。

数据示例

const respProducts = [
    {
        "cursor": "eyJsYXN0X2lkIjo4OT234234sYXN0X3ZhbHVlIjo4OTkzOTgyMjExfQ==",
        "node": {
            "id": "gid://shopify/Product/8923422211",
            "title": "California Here"
        }
    },
    {
        "cursor": "eyJsYXN0X2lkIjo5234234sYXN0X3ZhbHVlIjo5MDExNDM0MzA3fQ==",
        "node": {
            "id": "gid://shopify/Product/923423434307",
            "title": "Texas 2000 Here"
        }
    },
    {
        "cursor": "eyJsYXN0X2lkIj234234LCJsYXN0X3ZhbHVlIjo5MzM4MDczODcwfQ==",
        "node": {
            "id": "gid://shopify/Product/23423470",
            "title": "Texas Black Here"
        }
    }
]

const currentTemplates = {
    "Texas 2000 Here": {
        "productTemplate": {},
        "colorVariants": false
    },
    "Alabama": {
        "productTemplate": {},
        "colorVariants": false
    },
    "Alaska": {
        "productTemplate": {},
        "colorVariants": false
    },
    "Arizona": {
        "productTemplate": {},
        "colorVariants": false
    }
}

错误尝试代码

const respBuildArray = respProducts.filter(el => el.node.title.includes(Object.keys(currentTemplates).map(el => el)));

问题分析

这段代码有两个核心错误:

  1. 逻辑方向反了:我们需要保留的是node.title不匹配currentTemplates键名的元素,而不是匹配的。
  2. 方法使用错误:String.includes()是判断字符串是否包含某个子串,你传入的是一个数组,这永远会返回false;而且判断是否存在于对象键名里,应该用对象的键名检查方法,比如Object.hasOwn()或者直接判断键是否存在。

正确实现方式

方式一:直接检查对象键名

// 过滤掉node.title在currentTemplates键名中的元素
const respBuildArray = respProducts.filter(el => !Object.hasOwn(currentTemplates, el.node.title));

方式二:用Set优化(数据量大时更高效)

如果currentTemplates的键名很多,先把键名转成Set可以提升查找效率:

const templateTitles = new Set(Object.keys(currentTemplates));
const respBuildArray = respProducts.filter(el => !templateTitles.has(el.node.title));

期望结果

const respBuildArray = [
    {
        "cursor": "eyJsYXN0X2lkIjo4OT234234sYXN0X3ZhbHVlIjo4OTkzOTgyMjExfQ==",
        "node": {
            "id": "gid://shopify/Product/8923422211",
            "title": "California Here"
        }
    },
    {
        "cursor": "eyJsYXN0X2lkIj234234LCJsYXN0X3ZhbHVlIjo5MzM4MDczODcwfQ==",
        "node": {
            "id": "gid://shopify/Product/23423470",
            "title": "Texas Black Here"
        }
    }
]

内容的提问来源于stack exchange,提问作者FabricioG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 08:57:15