2700. 两个对象之间的差异
2025年6月25日小于 1 分钟
2700. 两个对象之间的差异
type JSONValue =
| null
| boolean
| number
| string
| JSONValue[]
| { [key: string]: JSONValue }
type Obj = Record<string, JSONValue> | Array<JSONValue>
const isObject = (object: unknown) =>
typeof object === 'object' && object !== null
function type(obj: unknown): string {
return Object.prototype.toString.call(obj).slice(8, -1)
}
function objDiff(obj1: Obj, obj2: Obj): Obj {
// 类型不同
if (type(obj1) !== type(obj2)) return [obj1, obj2]
// 基础类型比较
if (!isObject(obj1)) return obj1 === obj2 ? {} : [obj1, obj2]
// 过滤非共同子项
const sameKeys = Object.keys(obj1).filter((key) => Object.hasOwn(obj2, key))
const diff: Obj = {}
// 遍历相同key
for (const key of sameKeys) {
const sub = objDiff((obj1 as any)[key], (obj2 as any)[key])
if (Object.keys(sub).length > 0) {
(diff as any)[key] = sub
}
}
return diff
}