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

基于两个JavaScript对象生成差异对比新对象的需求

对比两个JavaScript对象生成差异对象

需求明确:给定两个JavaScript对象data(旧数据)和data1(新数据),生成新对象ans,仅保留两个对象中属性值不同的键,每个键对应包含old(取自data)和new(取自data1)的子对象。

示例代码

const data = {
    name: "teahyung",
    fatherName: "kim-ji-hyung",
    age: 26
};

const data1 = {
    name: "jangkook",
    fatherName: "kim-ji-hyung",
    age: 23
};

// 期望输出
const ans = {
    name: {
        old: "teahyung",
        new: "jangkook"
    },
    age: {
        old: 26,
        new: 23
    }
};

实现方案

以下是两种适用于基础类型属性值的浅对比实现:

方法1:遍历键集合实现

const getDiffObject = (oldObj, newObj) => {
    // 获取两个对象的所有唯一键
    const allKeys = new Set([...Object.keys(oldObj), ...Object.keys(newObj)]);
    const diffResult = {};

    for (const key of allKeys) {
        // 值不同则存入结果对象
        if (oldObj[key] !== newObj[key]) {
            diffResult[key] = {
                old: oldObj[key],
                new: newObj[key]
            };
        }
    }

    return diffResult;
};

// 使用示例
const ans = getDiffObject(data, data1);
console.log(ans);

方法2:用reduce简化实现

const getDiffObject = (oldObj, newObj) => {
    return [...new Set([...Object.keys(oldObj), ...Object.keys(newObj)])]
        .reduce((acc, key) => {
            if (oldObj[key] !== newObj[key]) {
                acc[key] = { old: oldObj[key], new: newObj[key] };
            }
            return acc;
        }, {});
};

// 使用示例
const ans = getDiffObject(data, data1);
console.log(ans);

注意事项

  • 上述实现为浅对比:若属性值是对象、数组等引用类型,!==会因引用不同判定为差异。如需深层对比,需编写递归逻辑遍历嵌套结构。
  • 支持处理对象间的额外键:比如data1新增gender键而data没有时,该键会被纳入结果,old值为undefined,new值为对应属性值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 03:27:22