Skip to content

JavaScript compare two objects and get differences | Code

  • by

In JavaScript, you can compare two objects and get differences by iterating the object over the loop and checking for equality in both objects, if the values at any point don’t match we will update a flag, exit out of the loop, and return the specific key.

JavaScript compares two objects and gets differences

Simple example code gets the property of the difference between two objects in JavaScript.

<!DOCTYPE html>
<html>
<body>
  <script>
    const obj1 = {
      name: 'ABC',
      id: '123',
      isEmployed: true,
      age: 45,
      salary: 0,
      job: 'Developer'
    }
    const obj2 = {
     name: 'ABC',
     id: '123',
     isEmployed: true,
     age: 45,
     salary: 0,
     job: 'No Job'
   }
   const difference = (obj1, obj2) => {
     let keyFound = false;
     Object.keys(obj1).forEach(key => {
      if(obj1[key] !== obj2[key]){
        keyFound = key +" Key : " + obj1[key] +" & "+ obj2[key];
       return keyFound;
     }
   });
     return keyFound || -1;
   };
   console.log(difference(obj1, obj2));
 </script>
</body>
</html>

Output:

JavaScript compare two objects and get differences

Return differences between two Objects: You can use Object.keys() and Array.includes() to do that.

var data = {
  "48": "{\"sid\":\"48\",\"name\":\"title 1\"}",
  "77": "{\"sid\":\"77\",\"name\":\"The blahblah title\"}",
  "83": "{\"sid\":\"83\",\"name\":\"The blahblah derp\"}",
  "87": "{\"sid\":\"87\",\"name\":\"The derpy title 4\"}"
};

var obj1 = {
  "48": "{\"sid\":\"48\",\"name\":\"title 1\"}",
  "77": "{\"sid\":\"77\",\"name\":\"The blahblah title\"}"
};

var result = {};
var keys = Object.keys(obj1);

for (var key in data) {
 if (!keys.includes(key)) {
  result[key] = data[key];
 }
}

console.log(result);

Output:


{
  "83": "{\"sid\":\"83\",\"name\":\"The blahblah derp\"}",
  "87": "{\"sid\":\"87\",\"name\":\"The derpy title 4\"}"
}

JS compares two objects

var person1={first_name:"bob"};
var person2 = {first_name:"bob"}; 

//compare the two object
if(JSON.stringify(person1) === JSON.stringify(person2)){
    //objects are the same
}

Do comment if you have any doubts or suggestions on this Js object 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