Write a function `diff(obj1, obj2)` that returns an object showing only the keys that changed and their new values.
Problem Statement
Write a function `diff(obj1, obj2)` that returns an object showing only the keys that changed and their new values.
Complexity
Time Complexity: -
Space Complexity: -
Hints
š” Hint 1:
Compare each key in both objects.
š” Hint 2:
If values differ, add to the diff result.
š” Hint 3:
For nested objects, recurse. Only include keys that actually changed.
ā
Solution:
```javascript
function diff(obj1, obj2) {
const result = {};
const allKeys = new Set([...Object.keys(obj1), ...Object.keys(obj2)]);
for (const key of allKeys) {
if (typeof obj1[key] === "object" && typeof obj2[key] === "object" && obj1[key] !== null && obj2[key] !== null) {
const nested = diff(obj1[key], obj2[key]);
if (Object.keys(nested).length > 0) result[key] = nested;
} else if (obj1[key] !== obj2[key]) {
result[key] = obj2[key];
}
}
return result;
}
```