惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cloudbric
Cloudbric
T
Threat Research - Cisco Blogs
Simon Willison's Weblog
Simon Willison's Weblog
AWS News Blog
AWS News Blog
P
Privacy & Cybersecurity Law Blog
H
Help Net Security
云风的 BLOG
云风的 BLOG
G
GRAHAM CLULEY
Spread Privacy
Spread Privacy
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
A
Arctic Wolf
Project Zero
Project Zero
Engineering at Meta
Engineering at Meta
P
Privacy International News Feed
Blog — PlanetScale
Blog — PlanetScale
Stack Overflow Blog
Stack Overflow Blog
M
MIT News - Artificial intelligence
The Register - Security
The Register - Security
Recorded Future
Recorded Future
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
C
Cisco Blogs
PCI Perspectives
PCI Perspectives
Recent Announcements
Recent Announcements
Martin Fowler
Martin Fowler
A
About on SuperTechFans
W
WeLiveSecurity
GbyAI
GbyAI
V
Vulnerabilities – Threatpost
The GitHub Blog
The GitHub Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
Check Point Blog
Y
Y Combinator Blog
月光博客
月光博客
Scott Helme
Scott Helme
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google DeepMind News
Google DeepMind News
F
Fortinet All Blogs
U
Unit 42
G
Google Developers Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Threatpost
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Google Online Security Blog
Google Online Security Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Cisco Talos Blog
Cisco Talos Blog
博客园 - 三生石上(FineUI控件)
Hugging Face - Blog
Hugging Face - Blog
MongoDB | Blog
MongoDB | Blog
博客园 - 司徒正美

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
How to Compare Objects in JavaScript
Dmitri Pavlutin · 2020-06-08 · via Dmitri Pavlutin Blog

Comparing primitive values in JavaScript is simple. Just use any of the available equality operators, for example, strict equality:


'a' === 'c'; // => false

1 === 1; // => true


Objects, however, are more difficult to compare because they are structured data.

In this post, you will learn how to compare objects correctly in JavaScript.

Table of Contents

  • 1. Referential equality
  • 2. Manual comparison
  • 3. Shallow equality
  • 4. Deep equality
  • 5. Summary

1. Referential equality

JavaScript provides 3 ways to compare values:

  • The strict equality operator ===
  • The loose equality operator ==
  • Object.is() function

When comparing objects using any of the above, the comparison evaluates to true only if the compared values refer to the same object instance. This is referential equality.

If you want to learn more about values and references, then check this post.

Let's define the objects hero1 and hero2, and see the referential equality in practice:


const hero1 = {

name: 'Batman'

};

const hero2 = {

name: 'Batman'

};

hero1 === hero1; // => true

hero1 === hero2; // => false

hero1 == hero1; // => true

hero1 == hero2; // => false

Object.is(hero1, hero1); // => true

Object.is(hero1, hero2); // => false


Open the demo.

hero1 === hero1 evaluates to true because both operands point to the same object instance hero1.

On the other side, hero1 === hero2 evaluates to false because the operands hero1 and hero2 are different object instances.

Interestingly hero1 and hero2 objects have the same content: both have one property name with the value 'Batman'. Still, even comparing objects of the same structure, hero1 === hero2 evaluates to false.

Referential equality is useful when you'd like to compare object references, rather than their content.

But more often you'll need to compare the actual contents of the objects: the properties and their values. Let's see how to do this.

2. Manual comparison

A simple way to compare objects by content is to read the properties and compare them manually.

For example, let's write a special function isHeroEqual() that compares 2 hero objects:


function isHeroEqual(object1, object2) {

return object1.name === object2.name;

}

const hero1 = {

name: 'Batman'

};

const hero2 = {

name: 'Batman'

};

const hero3 = {

name: 'Joker'

};

console.log(isHeroEqual(hero1, hero2)); // => true

console.log(isHeroEqual(hero1, hero3)); // => false


Open the demo.

isHeroEqual() accesses the property name of both objects and compares their values.

If the compared objects have a few properties, I prefer to write the comparison functions like isHeroEqual(). Such functions have good performance — only a few property accessors and equality operators are involved in the comparison.

Manual comparison requires manual extraction of properties — for simple objects, that's not a problem. But to compare bigger objects (or objects of unknown structure), the manual comparison isn't convenient because it requires a lot of boilerplate code.

Let's see how the shallow equality of objects can help.

3. Shallow equality

During the shallow equality check of objects you get the list of properties (using Object.keys()) of both objects, then check the properties' values for equality.

Here's a possible implementation of shallow equality check:


function shallowEqual(object1, object2) {

const keys1 = Object.keys(object1);

const keys2 = Object.keys(object2);

if (keys1.length !== keys2.length) {

return false;

}

for (let key of keys1) {

if (object1[key] !== object2[key]) {

return false;

}

}

return true;

}


Inside the function, keys1 and keys2 are arrays containing the property names of object1 and object2.

for cycle iterates over the keys, and compares objects' properties (object1[key] and object2[key]) for equality.

Let's use shallow equality to compare objects with many properties:


const hero1 = {

name: 'Batman',

realName: 'Bruce Wayne'

};

const hero2 = {

name: 'Batman',

realName: 'Bruce Wayne'

};

const hero3 = {

name: 'Joker'

};

console.log(shallowEqual(hero1, hero2)); // => true

console.log(shallowEqual(hero1, hero3)); // => false


Open the demo.

shallowEqual(hero1, hero2) returns true because the objects hero1 and hero2 have the same properties (name and realName) with the same values.

On the other side, shallowEqual(hero1, hero3) returns false since hero1 and hero3 have different properties.

If the properties' values of objects to compare are primitive values, then the shallow equality check is the way to go.

But objects in JavaScript can be nested. In this case, unfortunately, shallow equality doesn't work well.

Let's perform a shallow equality check on objects having nested objects:


const hero1 = {

name: 'Batman',

address: {

city: 'Gotham'

}

};

const hero2 = {

name: 'Batman',

address: {

city: 'Gotham'

}

};

console.log(shallowEqual(hero1, hero2)); // => false


Open the demo.

This time, even hero1 and hero2 have the same content, shallowEqual(hero1, hero2) returns false.

The nested objects hero1.address and hero2.address are different object instances. Thus shallow equality considers hero1.address and hero2.address to be not equal.

Fortunately, the deep equality correctly compares the objects that contain other objects. Let's take a look at how this works.

4. Deep equality

Deep equality is similar to shallow equality, but with one difference. During the object check, if the values being compared are objects, then a recursive equality check is performed on these nested objects.

Let's look at the implementation of a deep equality check:


function deepEqual(object1, object2) {

const keys1 = Object.keys(object1);

const keys2 = Object.keys(object2);

if (keys1.length !== keys2.length) {

return false;

}

for (const key of keys1) {

const val1 = object1[key];

const val2 = object2[key];

const areObjects = isObject(val1) && isObject(val2);

if (

areObjects && !deepEqual(val1, val2) ||

!areObjects && val1 !== val2

) {

return false;

}

}

return true;

}

function isObject(object) {

return object != null && typeof object === 'object';

}


The highlighted line areObjects && !deepEqual(val1, val2) indicates that as soon as the compared properties are objects, a recursive call starts to verify whether the nested objects are equal too.

Now, let's see an example of deepEquality():


const hero1 = {

name: 'Batman',

address: {

city: 'Gotham'

}

};

const hero2 = {

name: 'Batman',

address: {

city: 'Gotham'

}

};

console.log(deepEqual(hero1, hero2)); // => true


Open the demo.

The deep equality function correctly determines that hero1 and hero2 have the same properties and values, including the equality of the nested objects hero1.address and hero2.address.

To deeply compare objects I recommend to use:

5. Summary

The referential equality (using ===, == or Object.is()) determines whether the operands are the same object instance.

The manual equality check requires a manual comparison of properties' values. Although this check requires writing down the properties to be compared by hand, I find this approach convenient because of its simplicity.

If the objects being compared have a lot of properties or if the structure of the objects is determined at runtime, a better approach is to use a shallow check.

Finally, if the compared objects have nested objects, the deep equality check is the way to go.

What is the main issue when using JSON.stringify(object1) === JSON.stringify(object2) to compare objects?