2700. Differences Between Two Objects
https://leetcode.com/problems/differences-between-two-objects/
Javascript
function objDiff(obj1, obj2) {
// 1: Pure value
if (!isObject(obj1) && !isObject(obj2)) {
return obj1 === obj2 ? {} : [obj1, obj2]
}
// 2. Only one of them is Null or Array
if (!isObject(obj1) || !isObject(obj2)) {
return [obj1, obj2]
}
// 3. Array
if (Array.isArray(obj1) !== Array.isArray(obj2)) {
return [obj1, obj2]
}
// 4. Compare recursive
const diffs = {}
for (const key in obj1) {
if (!(key in obj2)) {
continue
}
const result = objDiff(obj1[key], obj2[key])
if (Object.keys(result).length) {
diffs[key] = result
}
}
return diffs
}
function isObject(obj) {
return obj !== null && typeof obj === "object"
}