Object difference in JavaScript

In JavaScript, finding the difference between two objects means identifying keys that exist in the first object but not in the second. This is useful for comparing data structures, tracking changes, or filtering object properties.

Problem Statement

We need to write a JavaScript function that takes two objects (possibly nested) and returns a new object containing only the key-value pairs that exist in the first object but are missing from the second object.

Basic Implementation

Here's a function that compares two objects and returns the difference:

const obj1 = {
   "firstName": "Raghav",
   "lastName": "Raj",
   "age": 43,
   "address": "G-12 Kalkaji",
   "email": "raghavraj1299@yahoo.com",
   "salary": 90000
};

const obj2 = {
   "lastName": "Raj",
   "address": "G-12 Kalkaji",
   "email": "raghavraj1299@yahoo.com",
   "salary": 90000
};

const objectDifference = (first, second) => {
   return Object.keys(first).reduce((acc, val) => {
      if(!second.hasOwnProperty(val)){
         acc[val] = first[val];
      }
      return acc;
   }, {});
};

console.log(objectDifference(obj1, obj2));
{ firstName: 'Raghav', age: 43 }

How It Works

The function uses Object.keys() to get all keys from the first object, then reduce() to build a new object. For each key, it checks if the key exists in the second object using hasOwnProperty(). If the key is missing from the second object, it's added to the result.

Alternative Implementation Using Object.entries()

Here's another approach using Object.entries() and Object.fromEntries():

const objectDifferenceAlt = (first, second) => {
   return Object.fromEntries(
      Object.entries(first).filter(([key]) => !(key in second))
   );
};

const testObj1 = { a: 1, b: 2, c: 3 };
const testObj2 = { b: 2, c: 3 };

console.log(objectDifferenceAlt(testObj1, testObj2));
{ a: 1 }

Handling Nested Objects

For deep comparison of nested objects, we need a more sophisticated approach:

const deepObjectDifference = (first, second) => {
   const result = {};
   
   for (let key in first) {
      if (first.hasOwnProperty(key)) {
         if (!(key in second)) {
            result[key] = first[key];
         } else if (typeof first[key] === 'object' && first[key] !== null) {
            const nestedDiff = deepObjectDifference(first[key], second[key]);
            if (Object.keys(nestedDiff).length > 0) {
               result[key] = nestedDiff;
            }
         }
      }
   }
   
   return result;
};

const nestedObj1 = {
   name: "John",
   details: { age: 30, city: "New York" },
   hobbies: ["reading"]
};

const nestedObj2 = {
   details: { age: 30 },
   hobbies: ["reading"]
};

console.log(deepObjectDifference(nestedObj1, nestedObj2));
{ name: 'John', details: { city: 'New York' } }

Common Use Cases

  • Form Validation: Finding missing required fields
  • API Updates: Identifying changed properties before sending updates
  • Configuration Management: Comparing default vs. custom settings
  • Data Migration: Finding incomplete records during data transfer

Conclusion

Object difference functions help identify missing properties between objects. Use the basic implementation for simple comparisons, or the recursive version for nested objects. This technique is essential for data validation and change detection in JavaScript applications.

Updated on: 2026-03-15T23:18:59+05:30

176 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements