2755. 深度合并两个对象
2025年6月25日小于 1 分钟
2755. 深度合并两个对象
type JSONValue =
| null
| boolean
| number
| string
| JSONValue[]
| { [key: string]: JSONValue }
| null
| boolean
| number
| string
| JSONValue[]
| { [key: string]: JSONValue }
type JSONObject = { [key: string]: JSONValue }
function isObject(value: JSONValue): value is JSONObject {
return typeof value === 'object'
}
const type = (obj: any) => Object.prototype.toString.call(obj).slice(8, -1)
function deepMerge(obj1: JSONValue, obj2: JSONValue): JSONValue {
if (obj1 === null) return obj2
if (type(obj1) !== type(obj2)) return obj2
if (Array.isArray(obj1) && Array.isArray(obj2)) {
const result: JSONValue = [...obj1]
for (let i = 0; i < obj2.length; i++) {
if (isObject(result[i])) {
result[i] = deepMerge(result[i], obj2[i])
} else {
result[i] = obj2[i]
}
}
return result
}
if (isObject(obj1) && isObject(obj2)) {
const result: JSONObject = { ...obj1 }
for (const key in obj2) {
if (key in obj1) {
result[key] = deepMerge(obj1[key], obj2[key])
} else {
result[key] = obj2[key]
}
}
return result
}
return obj2
}