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

如何检查数组值是否存在于对象数组并添加指定属性?

如何根据指定数组匹配对象数组并添加属性?

需求说明

现有数组 const factArr = ['743156', '743157'],以及一个包含多个对象的数组(结构如下):

[
    {
        "id": null,
        "name": null,
        "adsFactId": "743156"
    },
    {
        "id": null,
        "name": null,
        "adsFactId": "743157"
    },
    {
        "id": null,
        "name": null,
        "adsFactId": "743158"
    },
    {
        "id": null,
        "name": null,
        "adsFactId": "743159"
    },
    {
        "id": null,
        "name": null,
        "adsFactId": "743976"
    },
    {
        "id": null,
        "name": null,
        "adsFactId": "744961"
    },
    {
        "id": null,
        "name": null,
        "adsFactId": "746809"
    },
    {
        "id": null,
        "name": null,
        "adsFactId": "747229"
    },
    {
        "adsId": null,
        "name": null,
        "adsFactId": "747231"
    },
    {
        "id": null,
        "name": null,
        "adsFactId": "749059"
    }
]

需要给对象数组中adsFactId与factArr中值匹配的对象,添加checked: true和checkBoxPatched: true两个属性,未匹配的对象保留原结构。

实现方案

基础实现(使用Array.map + includes)

通过Array.map()遍历对象数组,判断每个对象的adsFactId是否存在于factArr中,匹配则扩展对象添加属性,否则返回原对象:

const factArr = ['743156', '743157'];
const objArray = [/* 你的对象数组 */];

const processedArray = objArray.map(item => {
    // 检查当前对象的adsFactId是否在目标数组中
    if (factArr.includes(item.adsFactId)) {
        // 扩展原对象,添加新属性(不修改原对象)
        return {
            ...item,
            checked: true,
            checkBoxPatched: true
        };
    }
    // 不匹配则返回原对象
    return item;
});

性能优化版(使用Set提升查找效率)

如果factArr元素较多,includes()的O(n)查找效率较低,可将factArr转为Set,利用Set的O(1)查找特性优化性能:

const factArr = ['743156', '743157'];
const objArray = [/* 你的对象数组 */];

// 将目标数组转为Set,提升查找速度
const factSet = new Set(factArr);

const processedArray = objArray.map(item => {
    if (factSet.has(item.adsFactId)) {
        return {
            ...item,
            checked: true,
            checkBoxPatched: true
        };
    }
    return item;
});

可选:直接修改原对象数组

如果不需要保留原对象数组的纯净性,可以直接遍历修改原对象:

const factSet = new Set(factArr);
objArray.forEach(item => {
    if (factSet.has(item.adsFactId)) {
        item.checked = true;
        item.checkBoxPatched = true;
    }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 00:52:34