search
HomeWeb Front-endJS TutorialSeveral ways to compare objects in JavaScript

Several ways to compare objects in JavaScript

Dec 24, 2020 pm 05:59 PM
javascriptCompare objects

The following article will give you four ways to correctly compare JavaScript objects. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Several ways to compare objects in JavaScript

#Comparing raw values ​​in JavaScript is very simple. Just use any of the available equality operators, such as the strict equality operator:

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

But objects have structured data, so comparison is difficult. In this article, you will learn how to correctly compare objects in JavaScript.

1. Reference comparison

JavaScript provides 3 methods for comparing values:

  • Strict equality operator ===
  • Loose equality operator==
  • Object.is() Function

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

Let's define objects hero1 and hero2 and see reference equality in action:

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

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

On the other hand, hero1 === hero2 evaluates to false because hero1 and hero2 are Different object instances.

Interestingly, the contents of the hero1 and hero2 objects are the same: both objects have a name attribute, and its other The value is 'Batman'. Still, even when comparing objects of the same structure, hero1 === hero2 results in false.

Reference equality is useful when you want to compare object references rather than their contents. But more often than not, you want to compare objects based on their actual contents: properties and their values, for example.

Next let’s look at how to compare objects for equality through their contents.

2. Manual comparison

The most straightforward way to compare objects by content is to read the properties and compare them manually.

For example, let us write a special function isHeroEqual() to compare two hero objects:

function isHeroEqual(object1, object2) {
  return object1.name === object2.name;
}

const hero1 = {
  name: 'Batman'
};
const hero2 = {
  name: 'Batman'
};
const hero3 = {
  name: 'Joker'
};

isHeroEqual(hero1, hero2); // => true
isHeroEqual(hero1, hero3); // => false

isHeroEqual() Access both Object's properties name and compare their values.

If the object being compared has some properties, I prefer to write a comparison function 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, which is not a problem for simple objects. However, comparing larger objects (or objects whose structure is unknown) is inconvenient because it requires a lot of boilerplate code.

So let’s see how shallow comparison of objects can help.

3. Shallow comparison

If you use shallow comparison to check objects, you must get the property list of both objects (using Object.keys() ), and then check whether their attribute values ​​are equal.

The following code is an implementation method of shallow comparison:

function shallowEqual(object1, object2) {
  const keys1 = Object.keys(object1);
  const keys2 = Object.keys(object2);

  if (keys1.length !== keys2.length) {
    return false;
  }

  for (let index = 0; index < keys1.length; index++) {
    const val1 = object1[keys1[index]];
    const val2 = object2[keys2[index]];
    if (val1 !== val2) {
      return false;
    }
  }

  return true;
}

Inside the function, keys1 and keys2 contain ## respectively. Array of #object1 and object2 attribute names.

Use

for to loop through the keys and compare each property of object1 and object2.

Using shallow comparison, you can easily check equality on objects with many properties:

const hero1 = {
  name: &#39;Batman&#39;,
  realName: &#39;Bruce Wayne&#39;
};
const hero2 = {
  name: &#39;Batman&#39;,
  realName: &#39;Bruce Wayne&#39;
};
const hero3 = {
  name: &#39;Joker&#39;
};

shallowEqual(hero1, hero2); // => true
shallowEqual(hero1, hero3); // => false

shallowEqual(hero1, hero2) Returns true, because objects hero1 and hero2 have the same properties (name and realName), and the values ​​are also the same.

On the other hand, since

hero1 and hero3 have different properties, shallowEqual(hero1, hero3) will return false.

But objects in JavaScript can be nested. Shallow comparisons don't work well in this case.

The following performs a shallow comparison check on objects with nested objects:

const hero1 = {
  name: &#39;Batman&#39;,
  address: {
    city: &#39;Gotham&#39;
  }
};
const hero2 = {
  name: &#39;Batman&#39;,
  address: {
    city: &#39;Gotham&#39;
  }
};

shallowEqual(hero1, hero2); // => false

This time, even with two objects

hero1 and hero2 With the same content, shallowEqual(hero1, hero2) will also return false.

This happens because the nested objects

hero1.address and hero2.address are different object instances. Therefore, shallow comparison considers hero1.address and hero2.address to be two different values.

Solving the problem of nested objects requires deep comparison.

4. Deep comparison

Deep comparison is similar to shallow comparison, except that when an object is contained in a property, a recursive shallow comparison will be performed on the nested object. layer comparison.

Look at the implementation of deep comparison:

function deepEqual(object1, object2) {
  const keys1 = Object.keys(object1);
  const keys2 = Object.keys(object2);

  if (keys1.length !== keys2.length) {
    return false;
  }

  for (let index = 0; index < keys1.length; index++) {
    const val1 = object1[keys1[index]];
    const val2 = object2[keys2[index]];
    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 === &#39;object&#39;;
}

第 13 行的 areObjects && !deepEqual(val1, val2)  一旦检查到的属性是对象,则递归调用将会开始验证嵌套对象是否也相等。

现在用 deepEquality() 比较具有嵌套对象的对象:

const hero1 = {
  name: &#39;Batman&#39;,
  address: {
    city: &#39;Gotham&#39;
  }
};
const hero2 = {
  name: &#39;Batman&#39;,
  address: {
    city: &#39;Gotham&#39;
  }
};

deepEqual(hero1, hero2); // => true

深度比较函数能够正确地确定 hero1hero2 是否具有相同的属性和值,包括嵌套对象  hero1.address  和 hero2.address 的相等性。

为了深入比较对象,我建议使用Node内置util模块的  isDeepStrictEqual(object1, object2)  或lodash 库的 _.isEqual(object1, object2)

5. 总结

引用相等性(使用  =====Object.is())用来确定操作数是否为同一个对象实例。

手动检查对象是否相等,需要对属性值进行手动比较。尽管这类检查需要手动编码来对属性进行比较,但由于很简单,所以这种方法很方便。

当被比较的对象有很多属性或在运行时确定对象的结构时,更好的方法是使用浅层检查。

如果比较的对象具有嵌套对象,则应该进行深度比较检查。

英文原文地址:https://dmitripavlutin.com/how-to-compare-objects-in-javascript/

作者:Dmitri Pavlutin

译文地址:https://segmentfault.com/a/1190000022913676

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of Several ways to compare objects in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

How do I install JavaScript?How do I install JavaScript?Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool