javascript find diff in nested objects node js

function findNestedObjectDiff(obj1, obj2) {
  const diff = {};

  function compareObjects(obj1, obj2, path) {
    for (const key in obj1) {
      const currentPath = path ? `${path}.${key}` : key;

      if (typeof obj1[key] === 'object' && typeof obj2[key] === 'object') {
        compareObjects(obj1[key], obj2[key], currentPath);
      } else {
        if (obj1[key] !== obj2[key]) {
          diff[currentPath] = { oldValue: obj1[key], newValue: obj2[key] };
        }
      }
    }
  }

  compareObjects(obj1, obj2, '');

  return diff;
}

const object1 = {
  a: 1,
  b: {
    c: 2,
    d: {
      e: 3,
      f: 4
    }
  }
};

const object2 = {
  a: 1,
  b: {
    c: 2,
    d: {
      e: 5,
      g: 6
    }
  }
};

const result = findNestedObjectDiff(object1, object2);
console.log(result);

Explanation:

  1. findNestedObjectDiff is a function that takes two objects (obj1 and obj2) as parameters and returns an object representing the differences between them.

  2. Inside the function, an empty object called diff is initialized to store the differences.

  3. The compareObjects function is defined within findNestedObjectDiff. It recursively compares nested objects and populates the diff object with the paths of differing values along with their corresponding old and new values.

  4. The for...in loop is used to iterate through the keys of the first object (obj1).

  5. The currentPath variable is constructed to represent the current path in the nested structure.

  6. If the values at the current key in both objects are objects themselves, the compareObjects function is called recursively with the nested objects and the updated path.

  7. If the values are not objects, a check is performed to see if they are equal. If not, the difference is recorded in the diff object.

  8. The main function is called with the initial empty string as the starting path.

  9. The example objects (object1 and object2) are defined with nested structures.

  10. The findNestedObjectDiff function is called with the example objects, and the result is printed to the console.