Get the property of the difference between two objects in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

Let’s say, we are given two objects that have similar key value pairs with one or key having different values in both objects. Our job is to write a function that takes in the two objects as argument and returns the very first key it finds having different values. If all the keys have exact same values, it should return -1.

Here are the sample objects −

const obj1 = {
   name: 'Rahul Sharma',
   id: '12342fe4554ggf',
   isEmployed: true,
   age: 45,
   salary: 190000,
   job: 'Full Stack Developer',
   employedSince: 2005
}
const obj2 = {
   name: 'Rahul Sharma',
   id: '12342fe4554ggf',
   isEmployed: true,
   age: 45,
   salary: 19000,
   job: 'Full Stack Developer',
   employedSince: 2005
}

We will take in the two objects, iterate over the first one using forEach() loop, 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. If we iterate through the whole loop, it means that everything matched, in that case we will return -1.

The full code for this will be −

Example

const obj1 = {
   name: 'Rahul Sharma',
   id: '12342fe4554ggf',
   isEmployed: true,
   age: 45,
   salary: 190000,
   job: 'Full Stack Developer',
   employedSince: 2005
}
const obj2 = {
   name: 'Rahul Sharma',
   id: '12342fe4554ggf',
   isEmployed: true,
   age: 45,
   salary: 19000,
   job: 'Full Stack Developer',
   employedSince: 2005
}
const difference = (obj1, obj2) => {
   let keyFound = false;
   Object.keys(obj1).forEach(key => {
      if(obj1[key] !== obj2[key]){
         return keyFound = key;
      }
   });
   return keyFound || -1;
};
console.log(difference(obj1, obj2));

Output

The output in the console will be −

salary
raja
Published on 19-Aug-2020 07:05:18
Advertisements