Compare Two JSON Objects and Return a New JSON Object with Only Changes
Introduction:
In the domain of programming, comparing JSON objects to identify differences and changes is a common task. By implementing a structured approach, we can efficiently compute and present the variations between two JSON objects in a new JSON object.
Implementation:
- Initialize Variables:
- Create two JSON objects,
obj1
andobj2
, to represent the original and modified JSON data, respectively. - Initialize an empty JSON object,
obj3
, to store the differences between the two objects.
- Create two JSON objects,
- Traverse Object Keys:
- Utilize a
for
loop to iterate through the keys ofobj1
. - For each key, check whether
obj2
possesses the same key.
- Utilize a
- Comparison and Storage:
- If
obj2
does not have the current key, it signifies a difference. Store the key and its value fromobj1
inobj3
. - If the values associated with the key in
obj1
andobj2
are different, update the value inobj3
with the value fromobj2
.
- If
- Handle Nested Objects:
- If the values associated with the key are objects, recursively call the comparison function on these nested objects.
- This ensures that changes within nested objects are also captured and stored in
obj3
.
- Return Result:
- After processing all keys in
obj1
,obj3
will contain the differences between the two JSON objects. - Return
obj3
as the final result.
- After processing all keys in
Code Example:
function compareJSON(obj1, obj2) { var obj3 = {}; for (var key in obj1) { if (!obj2.hasOwnProperty(key)) { obj3[key] = obj1[key]; } else if (typeof obj1[key] === "object" && typeof obj2[key] === "object") { obj3[key] = compareJSON(obj1[key], obj2[key]); } else if (obj1[key] !== obj2[key]) { obj3[key] = obj2[key]; } } return obj3; } var obj1 = { "name": "John Doe", "age": 30, "address": { "street": "123 Main Street", "city": "Anytown", "state": "CA" } }; var obj2 = { "name": "Jane Smith", "age": 35, "address": { "street": "456 Elm Street", "city": "Anytown", "state": "CA" } }; var obj3 = compareJSON(obj1, obj2); console.log(obj3);
Output:
{ "name": "Jane Smith", "age": 35, "address": { "street": "456 Elm Street" } }In this example, we have two JSON objects,
obj1
and obj2
, with some differences in values and a nested object. The compareJSON
function successfully identifies these changes and returns a new JSON object, obj3
, containing only the variations.
By employing this approach, you can compare two JSON objects and obtain a concise representation of their differences in a new JSON object. This technique proves useful in various scenarios requiring data comparison and change tracking.