Q19: Calculate Structural Difference Between Two Objects
Implement diffObjects(obj1, obj2) to compare two objects recursively and return a summary of added, removed, and updated properties.
Object Diffing Utility
function diffObjects(obj1, obj2) {
const diff = {};
const allKeys = new Set([...Object.keys(obj1), ...Object.keys(obj2)]);
for (let key of allKeys) {
if (!(key in obj1)) {
diff[key] = { status: 'ADDED', value: obj2[key] };
} else if (!(key in obj2)) {
diff[key] = { status: 'REMOVED', value: obj1[key] };
} else if (typeof obj1[key] === 'object' && typeof obj2[key] === 'object' && obj1[key] !== null && obj2[key] !== null) {
const nestedDiff = diffObjects(obj1[key], obj2[key]);
if (Object.keys(nestedDiff).length > 0) diff[key] = nestedDiff;
} else if (obj1[key] !== obj2[key]) {
diff[key] = { status: 'UPDATED', oldValue: obj1[key], newValue: obj2[key] };
}
}
return diff;
}💡 Collects keys across both objects to determine property additions, removals, and value mutations recursively.
Key Takeaways
- Combines key sets to evaluate deletions, additions, and mutations.
- Recursively evaluates nested object structures to identify structural changes.
Knowledge Check
How does the diffObjects algorithm identify a key that was REMOVED in obj2?