Skip to main content
InterviewHubPRO
Section Overview
Q535

Question 535 of 536

Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 536)

100%
JavaScript & V8 Internals (536 Qs)•Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 536)

How do you implement a deep object diff function to detect added, modified, and deleted properties?

mid LevelCode ExampleFormsPerformanceHTTP & REST APIs

In Simple Words: A deep object diff algorithm recursively compares two JSON trees to generate a patch summary identifying newly added keys, deleted keys, and modified values with their before-and-after states, essential for state synchronization, undo/redo stacks, and UI reconciliation.

Implementation

javascript
function isPlainObject(val) {
  return val !== null && typeof val === 'object' && !Array.isArray(val);
}

function diffObjects(oldObj, newObj) {
  const diff = {
    added: {},
    modified: {},
    deleted: {}
  };

  const oldKeys = Object.keys(oldObj || {});
  const newKeys = Object.keys(newObj || {});
  const allKeys = new Set([...oldKeys, ...newKeys]);

  for (const key of allKeys) {
    const hasOld = Object.prototype.hasOwnProperty.call(oldObj || {}, key);
    const hasNew = Object.prototype.hasOwnProperty.call(newObj || {}, key);

    // 1. Key added in newObj
    if (!hasOld && hasNew) {
      diff.added[key] = newObj[key];
      continue;
    }

    // 2. Key removed from newObj
    if (hasOld && !hasNew) {
      diff.deleted[key] = oldObj[key];
      continue;
    }

    // 3. Key exists in both: check equality or nested objects
    const oldVal = oldObj[key];
    const newVal = newObj[key];

    if (isPlainObject(oldVal) && isPlainObject(newVal)) {
      const nestedDiff = diffObjects(oldVal, newVal);
      if (
        Object.keys(nestedDiff.added).length > 0 ||
        Object.keys(nestedDiff.modified).length > 0 ||
        Object.keys(nestedDiff.deleted).length > 0
      ) {
        diff.modified[key] = nestedDiff;
      }
    } else if (Array.isArray(oldVal) && Array.isArray(newVal)) {
      if (JSON.stringify(oldVal) !== JSON.stringify(newVal)) {
        diff.modified[key] = { from: oldVal, to: newVal };
      }
    } else if (oldVal !== newVal) {
      diff.modified[key] = { from: oldVal, to: newVal };
    }
  }

  // Clean empty sections
  const result = {};
  if (Object.keys(diff.added).length > 0) result.added = diff.added;
  if (Object.keys(diff.modified).length > 0) result.modified = diff.modified;
  if (Object.keys(diff.deleted).length > 0) result.deleted = diff.deleted;

  return result;
}

// Verification:
const originalUser = {
  id: 101,
  name: "Marcus",
  role: "Engineer",
  skills: ["JavaScript", "Python"],
  profile: {
    theme: "light",
    notifications: true
  }
};

const updatedUser = {
  id: 101,
  name: "Marcus Aurelius", // modified
  // role is deleted
  skills: ["JavaScript", "TypeScript"], // modified
  department: "Infrastructure", // added
  profile: {
    theme: "dark", // nested modified
    notifications: true
  }
};

console.log(JSON.stringify(diffObjects(originalUser, updatedUser), null, 2));
/*
Output:
{
  "added": { "department": "Infrastructure" },
  "modified": {
    "name": { "from": "Marcus", "to": "Marcus Aurelius" },
    "skills": { "from": ["JavaScript", "Python"], "to": ["JavaScript", "TypeScript"] },
    "profile": {
      "modified": {
        "theme": { "from": "light", "to": "dark" }
      }
    }
  },
  "deleted": { "role": "Engineer" }
}
*/