Skip to content

Compare two JSON objects and get different JavaScript

  • by

Simple run a for loop over the first JSON object and check whether the second one has it or not to Compare two JSON objects and get different JavaScript.

 var obj3={};
 for (var key in obj1)
 {
    !obj2.hasOwnProperty(key) && obj3[key]=obj[key];

 }

Compare two JSON objects and get different JavaScript

Simple example code Compare two JSON objects and return the other JSON object with only the change in JavaScript.

Assume there are 2 JSON objects, one is with old data and another one is new. With this function, you can get the difference between this version of data.

<!DOCTYPE html>
<html>
<body>

  <script>
    var obj1 = {
     "_id":"3fad6024-3226-451b-9e81-1c544aaaebf7",
     "name":"ank retailer part 2",
     "aboutUs":"i am about us",
     "agents":[
     {
       "agentID":"89add463-7cb7-442a-b705-405e03f7e86a"
     },
     {
       "agentID":"1c98d888-6c43-463c-b7ed-79ea8736125f"
     }
     ],
     "retailerLanguage":[

     {
       "languageID":"20b4772c-2470-4eaa-bc0c-61429700781c", language: {name: "Korean", __typename: "language"}
     },
     {
       "languageID":"8f04da56-0f53-4694-b6dc-0eb5a3aa2990", language: {name: "Mandarin", __typename: "language"}
     },
     ],

     "termsAndConditions":"agreed"
   };

   var obj2 = {
     "_id":"3fad6024-3226-451b-9e81-1c544aaaebf7",
     "name":"ank retailer part 2",
     "aboutUs":"i am about us",
     "agents":[
     {
       "agentID":"89add463-7cb7-442a-b705-405e03f7e86a"
     },
     {
       "agentID":"1c98d888-6c43-463c-b7ed-79ea8736125f"
     }
     ],
     "retailerLanguage":[

     {
       "languageID":"20b4772c-2470-4eaa-bc0c-61429700781c", language: {name: "Korean", __typename: "language"}
     },
     {
       "languageID":"8f04da56-0f53-4694-b6dc-0eb5a3aa2990", language: {name: "Mandarin", __typename: "language"}
     },
     ],

     "termsAndConditions":"agreed"
   }
   var diffParams = {};

   for( var p in obj1 ){
    if ( !compareValue(obj1[p] && obj1[p],obj2[p]&& obj2[p]) ){
      diffParams[p] = obj1[p];
    }
  }
  
  function compareValue(val1, val2){
    var isSame = true;
    for ( var p in val1 ) {

      if (typeof(val1[p]) === "object"){
        var objectValue1 = val1[p],
        objectValue2 = val2[p];
        for( var value in objectValue1 ){
          isSame = compareValue(objectValue1[value], objectValue2[value]);
          if( isSame === false ){
            return false;
          }
        }
      }else{
        if(val1 !== val2){
          isSame = false;
        }
      }
    }
    return isSame;
  }

  var d = diffParams
  console.log("Difference", d)
</script>

</body>
</html>

Output:

Compare two JSON objects and get different JavaScript

There is a library for getting the structural differences between two objects https://github.com/flitbit/diff

Here’s a basic implementation to achieve that:

function compareJSONObjects(obj1, obj2) {
    const keys = new Set([...Object.keys(obj1), ...Object.keys(obj2)]);
    const differences = {};

    keys.forEach(key => {
        if (JSON.stringify(obj1[key]) !== JSON.stringify(obj2[key])) {
            differences[key] = {
                oldValue: obj1[key],
                newValue: obj2[key]
            };
        }
    });

    return differences;
}

// Example JSON objects
const obj1 = {
    name: "John",
    age: 30,
    city: "New York"
};

const obj2 = {
    name: "John",
    age: 31,
    city: "New York"
};

const diff = compareJSONObjects(obj1, obj2);
console.log(diff);

This code will output the differences between the two JSON objects:

{
    age: {
        oldValue: 30,
        newValue: 31
    }
}

This function compares the keys of both objects and checks if their stringified values are equal. If not, it adds the difference to the differences object, containing the old and new values.

Do comment if you have any doubts or suggestions on this Js Compare objects topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading