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:
findNestedObjectDiff
is a function that takes two objects (obj1
andobj2
) as parameters and returns an object representing the differences between them.Inside the function, an empty object called
diff
is initialized to store the differences.The
compareObjects
function is defined withinfindNestedObjectDiff
. It recursively compares nested objects and populates thediff
object with the paths of differing values along with their corresponding old and new values.The
for...in
loop is used to iterate through the keys of the first object (obj1
).The
currentPath
variable is constructed to represent the current path in the nested structure.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.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.The main function is called with the initial empty string as the starting path.
The example objects (
object1
andobject2
) are defined with nested structures.The
findNestedObjectDiff
function is called with the example objects, and the result is printed to the console.