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

使用原生JavaScript实现JSON对象去重及新拉取数据重复校验

原生JavaScript对象数组完全匹配去重方案

核心逻辑

  • 以licenceNum、state、country三个字段的组合作为唯一判断依据,拼接为字符串作为重复校验的key
  • 借助Set结构存储已存在的key,校验重复的时间复杂度为O(1),整体处理效率为O(n),适合大规模数据场景
  • 完全基于原生JS API实现,无需引入任何第三方依赖

一、现有数组去重代码

// 原始数组
const array = [
    { "licenceNum": "12345", state:"NV", country:"US" },
    { "licenceNum": "12345", state:"OR", country:"US" },
    { "licenceNum": "10849", state:"CA", country:"US" },
    { "licenceNum": "12345", state:"OR", country:"US" },
    { "licenceNum": "12345", state:"OR", country:"CA" },
    { "licenceNum": "22424", state:"OR", country:"CA" },
    { "licenceNum": "22424", state:"OR", country:"CA" },
    { "licenceNum": "12345", state:"NM", country:"US" },
    { "licenceNum": "A7846", state:"CA", country:"US" },
    { "licenceNum": "10849", state:"CA", country:"US" },
    { "licenceNum": "10849", state:"CA", country:"US" },
    { "licenceNum": "B7037", state:"WA", country:"US" }
];

// 完全匹配去重函数
function deduplicate(arr) {
    const existKeys = new Set();
    const result = [];
    for (const item of arr) {
        // 拼接三个字段为唯一key,分隔符可更换为不会出现在字段值中的任意字符
        const key = `${item.licenceNum}|${item.state}|${item.country}`;
        if (!existKeys.has(key)) {
            existKeys.add(key);
            result.push(item);
        }
    }
    return result;
}

// 生成去重后数组
const uniqueArray = deduplicate(array);

注:你给出的期望结果中遗漏了仅出现一次的licenceNum: A7846项,按完全去重逻辑该项会被保留,若不需要可自行添加对应过滤条件。

二、API新数据校验插入实现

每次拉取新数据后,先校验是否存在完全匹配的项,不存在再插入到已有去重数组中:

// 单独维护已存在的key集合,避免每次校验都遍历整个数组
let existKeySet = new Set(uniqueArray.map(item => `${item.licenceNum}|${item.state}|${item.country}`));

// 新数据插入处理函数
function addItemsIfNotExist(uniqueArr, newItems) {
    for (const item of newItems) {
        const key = `${item.licenceNum}|${item.state}|${item.country}`;
        if (!existKeySet.has(key)) {
            existKeySet.add(key);
            uniqueArr.push(item);
        }
    }
}

// 使用示例:拉取API新数据后调用即可
const newFetchedData = [
    // 已存在的重复项,不会被插入
    { "licenceNum": "12345", state:"OR", country:"US" },
    // 全新项,会正常插入
    { "licenceNum": "C9274", state:"NY", country:"US" }
];
addItemsIfNotExist(uniqueArray, newFetchedData);

可选调整

如果后续业务字段有变更,仅需修改key的拼接规则即可。若字段值可能包含分隔符|,也可以直接用JSON.stringify(item)作为key(需保证对象字段顺序固定,你的场景满足该条件)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 10:57:02