Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Get the Difference between Two Sets using JavaScript
Next article icon

Print Difference between Two Objects in JavaScript ?

Last Updated : 22 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Printing the difference between two objects in JavaScript involves comparing the properties of the two objects and identifying the discrepancies between them. This can include properties that exist in one object but not in the other, as well as properties with differing values.

These are the following ways:

Table of Content

  • Using for loop
  • Using Object.entries() and Array.prototype.reduce()

Using for loop

This approach involves iterating over the properties of one object and checking if they exist or have different values in the other object. You can accomplish this by using a loop (such as for...in) to iterate through the properties of one object and compare them with the corresponding properties in the other object.

Example: The findDifference function compares two objects and returns an object representing their differences. It checks keys in both objects, noting variations in values. The output highlights discrepancies between the objects, including missing keys.

JavaScript
function findDifference(obj1, obj2) {     const diffKeys = [];     for (const key in obj1) {         if (!(key in obj2) ||             obj1[key] !== obj2[key]) {             diffKeys.push(key);         }     }     for (const key in obj2) {         if (!(key in obj1) ||             obj1[key] !== obj2[key]) {             if (!diffKeys.includes(key)) {                 diffKeys.push(key);             }         }     }     return diffKeys; }  const obj1 = { a: 1, b: 2, c: 3 }; const obj2 = { a: 1, b: 4, d: 5 };  console.log(findDifference(obj1, obj2)); 

Output
[ 'b', 'c', 'd' ] 

Using Object.entries() and Array.prototype.reduce()

ES6 introduced several powerful features for working with objects and arrays, such as Object.entries() and Array.prototype.reduce(). Using these features, you can iterate over the properties of an object and compare them with another object.

Example: The Function takes two objects (obj1 and obj2) as arguments and returns an object representing the differences between them. It iterates through the keys of both objects, comparing their values. If a key exists in one object but not the other, or if the values of the same key differ, it records the difference. The final result is an object containing the discrepancies found in both objects.

JavaScript
function findDifference(obj1, obj2) {     const diffKeys = Object.keys(obj1)         .reduce((acc, key) => {             if (!(key in obj2) ||                 obj1[key] !== obj2[key]) {                 acc.push(key);             }             return acc;         }, []);      Object.keys(obj2).forEach(key => {         if (!(key in obj1) ||             obj1[key] !== obj2[key]) {             if (!diffKeys.includes(key)) {                 diffKeys.push(key);             }         }     });      return diffKeys; }  const obj1 = { a: 1, b: 2, c: 3 }; const obj2 = { a: 1, b: 4, d: 5 };  console.log(findDifference(obj1, obj2));  

Output
[ 'b', 'c', 'd' ] 

Next Article
Get the Difference between Two Sets using JavaScript

A

anjugaeu01
Improve
Article Tags :
  • JavaScript
  • Web Technologies

Similar Reads

  • Difference Between Objects and Prototypes in JavaScript
    Objects in JavaScriptThe Objects in JavaScript are instances of the class or constructors and they can hold properties and methods. These properties and methods can be unique to the object or inherited from the prototypes. The Objects can be created using the constructor functions, object literals,
    3 min read
  • Difference Between Variables and Objects in JavaScript
    The variables and objects are fundamental concepts but they serve different purposes. The Variables are used to store data values while objects are used to group related data and functions into a single entity. JavaScript VariableA variable in JavaScript is a named container that stores a value. It
    2 min read
  • Get the Difference between Two Sets using JavaScript
    To get the difference between two sets in JavaScript, you need to identify elements present in the first set but not in the second. This involves iterating over the first set and filtering out elements that are also found in the second set, ensuring efficient comparison. We can get the difference be
    2 min read
  • Difference Between Two Arrays in JavaScript?
    These are the following ways to Get the Difference Between Two Arrays in JavaScript: 1. Using the filter() and includes() Methods - Mostly UsedWe can use the filter() method on the first array and check if each item is not present in the second array using the includes() method. The resulting array
    3 min read
  • Difference between Array and Array of Objects in JavaScript
    ArrayAn Array is a collection of data and a data structure that is stored in a sequence of memory locations. One can access the elements of an array by calling the index number such as 0, 1, 2, 3, ..., etc. The array can store data types like Integer, Float, String, and Boolean all the primitive dat
    3 min read
  • Difference Between Object.assign and Spread Operator in JavaScript
    The Object.assign() and the Spread Operator (...) are commonly used for copying properties from one object to another. While they can achieve similar outcomes, they have distinct characteristics and use cases. This article will explain the differences between the Object.assign() and the spread opera
    3 min read
  • Difference Between for...in and Object.keys() in JavaScript
    The for...in and Object.keys() in JavaScript are used to iterate over the properties of an object. While they might seem similar at first glance they have distinct usage, behavior, and characteristics. This article will explore these differences in detail. These are the following topics that we are
    3 min read
  • Difference Between JavaScript and jQuery
    JavaScript is a programming language used for web development, while jQuery is a library written in JavaScript, simplifying tasks like DOM manipulation, event handling, and AJAX requests, making JavaScript code more concise and readable. JavaScriptJavaScript is a crucial scripting language for enhan
    6 min read
  • Difference between JavaScript and PHP
    In this article, we will know about Javascript & PHP, along with understanding their significant differences. A long time before, most people used to think PHP is a server-side language and Javascript as client-side language as it was only executed in web browsers. But after V8, Node and other f
    4 min read
  • Difference Between label and break in JavaScript
    The labels and the break statement are used within loops and control flow structures to enhance flexibility and manageability. Each serves distinct purposes and can be applied in the various scenarios based on the needs of the code. These are the following topics that we are going to discuss: Table
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences