0% found this document useful (0 votes)
3 views1 page

Diff

The document contains a JavaScript function that compares two JSON objects and identifies their differences. It recursively checks each key in both objects and records discrepancies in a structured format. The function outputs the differences, including nested properties, to the console.

Uploaded by

mrmarktyy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views1 page

Diff

The document contains a JavaScript function that compares two JSON objects and identifies their differences. It recursively checks each key in both objects and records discrepancies in a structured format. The function outputs the differences, including nested properties, to the console.

Uploaded by

mrmarktyy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

import left from "./left.

json" assert { type: "json" };


import right from "./right.json" assert { type: "json" };

function diffJson(obj1, obj2) {


function findDifferences(obj1, obj2, path = "") {
let differences = {};
const allKeys = new Set([...Object.keys(obj1), ...Object.keys(obj2)]);

allKeys.forEach((key) => {
const fullPath = path ? `${path}.${key}` : key;
const value1 = obj1[key];
const value2 = obj2[key];

if (
typeof value1 === "object" &&
value1 !== null &&
typeof value2 === "object" &&
value2 !== null
) {
const nestedDiff = findDifferences(value1, value2, fullPath);
if (Object.keys(nestedDiff).length > 0) {
differences = { ...differences, ...nestedDiff };
}
} else if (value1 !== value2) {
differences[fullPath] = { value1, value2 };
}
});

return differences;
}

return findDifferences(obj1, obj2);


}

console.log(diffJson(left, right));

You might also like