Alternative
Amazon
Article
Writing
Art
AI
Angular
Photoshop
Premiere
Animal Crossing
Blog
Story
Android
Android Studio
Davinci Resolve
CSS
Clipchamp
ChatGPT
Crypto
DALL-E
Discord
Davinci Resolve
Davinci Resolve 18
Dream Studio
Express
Filmora
Flutter
PC Games
Git
GPT
GPT3
GPT4
GTA
GTA 6
Ghost Together
Ghost Together
HTML
iOS
iMovie
Illustrator
JavaScript
Mac
Mongo
Midjourney
Minecraft
Node.js
NBA 2k24
OSX
PHP
Palworld
Python
Playground AI
Roblox
React
Recipe (Cooking)
React Native
Semicolon.dev
Starfield PC Game
Snapchat
Steam
Stable Diffusion
SVG
Threads
Text To Image (AI)
VSCode
Vim
Web Development
Windows
WebGL
Javascript Tutorials

How To Compare Two Objects In JavaScript Using Deep Equality

You can shallow or deep compare objects in JavaScript. Here's how to do it.

viewed 526 times
› tutorial › javascript › deep copy compare js objects

If you try to compare two objects in JavaScript as follows:

const a = {msg:"hello"}
const b = {msg:"hello"}

if (a === b) {
  console.log("True!")
}

You will get True printed in console. But appearance can be deceiving.

Strangely enough, JavaScript's === operator converts objects to "[Object object]" string.

Under the hood the actual comparison between two objects is done as:

if ("[Object object]" === "[Object object]") {
  console.log("True!")
}

This only happens because JavaScript first converted a and b objects to a string "[Object object]" and then compared those two strings! So, of course these two identical strings are "equal".

But that's not what is usually meant by comparing two objects.

We need to write our own function to compare objects in JavaScript.

Why doesn't JavaScript's === operator do a deep compare by default?

Think about it from standpoint of computer language design.

The reason why no programming language gives you its own deep comparison operator, is because due to potentially infinite complexity of an object, such functions can halt execution.

A built-in deep compare operator wouldn't be a good design choice for a programming language.

In most cases, when you want to do a deep-equality operation between two objects, you don't necessarily want an algorithm that gets stuck on infinitely nested object. (Which are common in languages like JavaScript, that support circular-dependencies.)

A circular dependency is when you have an object that contains references to itself. Running a deep equality operation on such objects will halt your program in an infinite while-loop.

Complex objects that appear in realistic computer programs are usually 2 or several levels deep. But probably no more than 5, 10 or more.

There is a difference between infinitely deep comparisons, and slightly more deeper than a shallow object comparison - which is the case you're most likely looking for.

The challenges of comparing two objects in JavaScript

It's easy to compare two simple objects in JavaScript. All you need to do is simply compare the number of, and values of each of its properties. You can use a for loop to do that. And this works with simple objects. Also known as "shallow" compare.

But what if your objects contain nested properties? The above technique will not work. You will need to compare nested values of each property in both objects. That's when things get a lot more complex. What if you don't know original size or structure of your object beforehand?

You will also need to be able to identify the type of each nested property. Is it a primitive value? An array? Or another object? Comparing arrays and comparing objects is done separately.

You need to deep copy compare it. (Go through each property in each object.) In this tutorial we'll take a look at a shallow compare and write our own deep equality comparison function.

What is the fastest way to do a shallow comparison (first-level properties only)?

To compare two objects in JavaScript, you can use the JSON.stringify() method to convert the objects to strings, and then compare the strings.

This is a common approach for comparing objects because it is a simple and reliable way to determine whether two objects have the same key-value pairs.

Here is an example of how to use JSON.stringify() to compare two objects:

var obj1 = {
  name: 'John',
  age: 30
};

var obj2 = {
  name: 'John',
  age: 30
};

var str1 = JSON.stringify(obj1);
var str2 = JSON.stringify(obj2);

if (str1 === str2) {
  console.log('The objects are equal.');
} else {
  console.log('The objects are not equal.');
}

This code first defines two objects, obj1 and obj2, which have the same key-value pairs. It then converts these objects to strings using JSON.stringify(), and saves the strings in the str1 and str2 variables.

Finally, it compares the two strings using the strict equality operator ===, and logs a message to the console indicating whether the objects are equal or not.

One thing to keep in mind when using this method to compare objects is that it only checks for shallow equality, meaning that it only compares the top-level properties of the objects.

If the objects have nested objects or arrays as properties, then these nested objects will not be compared.

For example, the following objects would be considered equal by this method, even though they have different nested objects:

var obj1 = {
  name: 'John',
  age: 30,
  nested: {
    foo: 'bar'
  }
};

var obj2 = {
  name: 'John',
  age: 30,
  nested: {
    baz: 'qux'
  }
};

A shallow comparison will consider the two objects above equal, but they're not.

How to do a deep copy comparison between two objects in JavaScript?

If you want to compare objects and also compare their nested objects, then you can use a deep equality function, which recursively compares the values of all the nested objects and arrays.

This is known as a deep copy, and it can be more complex and time-consuming than a shallow copy.

Here is an example of a deep equality function that you can use to compare objects in JavaScript:

function deepEqual(a, b) {

  // if either value is null or not an object, then they cannot be equal
  if (a == null || typeof a != 'object' ||
      b == null || typeof b != 'object') return false;

  // compare the lengths of the objects
  var keysA = Object.keys(a);
  var keysB = Object.keys(b);
  if (keysA.length != keysB.length) return false;

  // compare the key-value pairs of the objects
  for (var key of keysA) {
    if (!keysB.includes(key) || !deepEqual(a[key], b[key])) return false;
  }

  return true;
}

This function first checks if the two values are strictly equal using the === operator.

#javascript #js #deep #copy
Let's Ghost Together
Sign Up Now  -  It's Free!
Write For Us
Sign Up Now  -  It's Free!

How To Compare Two Objects In JavaScript Using Deep Equality

Comments (2) New! (You can now post comments on articles!)

(By posting a comment you are registering a Ghost Together account.)
Register
Register
Post It
DM Coming Soon
f f