How to compare Objects in TypeScript | bobbyhadz (2024)

How to compare Objects in TypeScript

# Table of Contents

  1. Comparing Objects in TypeScript
  2. Shallow Comparison of Objects in TypeScript
  3. Deep Comparison of Objects in TypeScript

# Comparing Objects in TypeScript

To compare objects in TypeScript:

  1. Use JSON.stringify() to compare objects whose keys are in the same order.
  2. Do a shallow comparison if the objects aren't nested.
  3. Use lodash.isEqual to test for deep equality of objects.

The JSON.stringify method can be used to compare objects when the order of thekeys in the two objects is the same.

index.ts

Copied!

type Person = { name: string; age: number;};const obj1: Person = { name: 'Bobby Hadz', age: 30,};const obj2: Person = { name: 'Bobby Hadz', age: 30,};if (JSON.stringify(obj1) === JSON.stringify(obj2)) { // 👇️ this runs console.log('✅ objects are equal');} else { console.log('⛔️ objects are NOT equal');}

How to compare Objects in TypeScript | bobbyhadz (1)

The code for this article is available on GitHub

We used theJSON.stringifymethod to convert the objects to strings and then we compared the results.

Note that this approach should only be used if the order of the keys in the twoobjects is the same.

For example, the following comparison returns false.

index.ts

Copied!

// 👇️ falseconsole.log( JSON.stringify({ age: 30, name: 'Bobby Hadz' }) === JSON.stringify({ name: 'Bobby Hadz', age: 30 }),);

How to compare Objects in TypeScript | bobbyhadz (2)

# Using the logical AND (&&) operator to compare objects

If your objects contain only a few key-value pairs that you know about inadvance, use the logical AND (&&) operator and compare the key-value pairs.

index.ts

Copied!

type Person = { name: string; age: number; country: string;};const obj1: Person = { country: 'Chile', name: 'Bobby Hadz', age: 30,};const obj2: Person = { age: 30, name: 'Bobby Hadz', country: 'Chile',};let areEqual = false;if ( obj1.name === obj2.name && obj1.age === obj2.age && obj1.country === obj2.country) { areEqual = true;}console.log(areEqual); // 👉️ true

How to compare Objects in TypeScript | bobbyhadz (3)

The code for this article is available on GitHub

The objects in the example only have a few key-value pairs that we can manuallycompare in an if statement without overcomplicating things.

# Shallow Comparison of Objects in TypeScript

If your objects don't have nested properties, you can do a relatively simpleshallow comparison.

index.ts

Copied!

type Person = { name: string; age: number;};const obj1: Person = { name: 'Bobby Hadz', age: 30,};const obj2: Person = { age: 30, name: 'Bobby Hadz',};// ✅ Shallow comparisonconst shallowComparison = Object.keys(obj1).length === Object.keys(obj2).length && (Object.keys(obj1) as (keyof typeof obj1)[]).every((key) => { return ( Object.prototype.hasOwnProperty.call(obj2, key) && obj1[key] === obj2[key] ); });console.log(shallowComparison); // 👉️ true

The code for this article is available on GitHub

We used theObject.keys()method to get an array of the keys of the two objects.

The next step is to check if the two objects have the same number of key-valuepairs.

If the key-value pair count of the two objects is not the same, then the objects are not equal.

The second comparison we did was to check if every key in the first objectexists in the second object.

We had to use atype assertionwhen typing the result of the Object.keys() method, because TypeScript setsthe type to string[] and we need the type of the array to only consist of theobject's keys.

The last thing we need to check is if the same keys in the two objects returnthe same values.

Theeverymethod will short-circuit, returning false if the condition isn't met at leastonce.

Otherwise, the every method returns true and the shallow equality checkpasses.

# Deep Comparison of Objects in TypeScript

The easiest way to perform a deep comparison of objects in TypeScript is toinstall and use the lodash.iseQuallibrary.

Open your terminal in the root directory of your project and install lodashwith the following 2 commands.

shell

Copied!

npm install lodash.isequalnpm install --save-dev @types/lodash.isequal

Now you can use the library to test the objects for deep equality.

index.ts

Copied!

import isEqual from 'lodash.isequal';type Person = { name: string; age: number; address: { country: string; city: string; };};const obj1: Person = { name: 'Bobby Hadz', age: 30, address: { country: 'Chile', city: 'Santiago', },};const obj2: Person = { address: { country: 'Chile', city: 'Santiago', }, age: 30, name: 'Bobby Hadz',};console.log(isEqual(obj1, obj2)); // 👉️ true

How to compare Objects in TypeScript | bobbyhadz (4)

The code for this article is available on GitHub

The isEqual method performs a deepcomparison between the passed-in values and returns a boolean result - true ifthey are equal and false otherwise.

The method supports comparing objects, arrays, Maps, Date objects, Sets, etc.

This is the preferred approach when you have to do a deep comparison of objects,because implementing a function that solves this problem is relativelycomplicated.

# Additional Resources

You can learn more about the related topics by checking out the followingtutorials:

  • How to merge Arrays in TypeScript
  • This comparison appears to be unintentional because the types 'X' and 'Y' have no overlap
  • Destructuring Object parameters in TypeScript functions
  • How to Remove a Property from an Object in TypeScript
  • How to initialize a typed Empty Object in TypeScript
  • A spread argument must either have a tuple type or be passed to a rest parameter
How to compare Objects in TypeScript | bobbyhadz (2024)
Top Articles
Latest Posts
Article information

Author: Prof. An Powlowski

Last Updated:

Views: 5843

Rating: 4.3 / 5 (44 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Prof. An Powlowski

Birthday: 1992-09-29

Address: Apt. 994 8891 Orval Hill, Brittnyburgh, AZ 41023-0398

Phone: +26417467956738

Job: District Marketing Strategist

Hobby: Embroidery, Bodybuilding, Motor sports, Amateur radio, Wood carving, Whittling, Air sports

Introduction: My name is Prof. An Powlowski, I am a charming, helpful, attractive, good, graceful, thoughtful, vast person who loves writing and wants to share my knowledge and understanding with you.