How to compare Objects in TypeScript

avatar
Borislav Hadzhiev

Last updated: Feb 27, 2024
4 min

banner

# 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 the keys in the two objects is the same.

index.ts
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'); }

comparing objects in typescript

The code for this article is available on GitHub

We used the JSON.stringify method 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 two objects is the same.

For example, the following comparison returns false.

index.ts
// ๐Ÿ‘‡๏ธ false console.log( JSON.stringify({ age: 30, name: 'Bobby Hadz' }) === JSON.stringify({ name: 'Bobby Hadz', age: 30 }), );

dont use when order of keys is not the same

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

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

index.ts
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

using logical and operator to compare objects

The code for this article is available on GitHub

The objects in the example only have a few key-value pairs that we can manually compare 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 simple shallow comparison.

index.ts
type Person = { name: string; age: number; }; const obj1: Person = { name: 'Bobby Hadz', age: 30, }; const obj2: Person = { age: 30, name: 'Bobby Hadz', }; // โœ… Shallow comparison const 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 the Object.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-value pairs.

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 object exists in the second object.

We had to use a type assertion when typing the result of the Object.keys() method, because TypeScript sets the type to string[] and we need the type of the array to only consist of the object's keys.

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

The every method will short-circuit, returning false if the condition isn't met at least once.

Otherwise, the every method returns true and the shallow equality check passes.

# Deep Comparison of Objects in TypeScript

The easiest way to perform a deep comparison of objects in TypeScript is to install and use the lodash.iseQual library.

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

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

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

index.ts
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

deep comparison of objects in typescript

The code for this article is available on GitHub

The isEqual method performs a deep comparison between the passed-in values and returns a boolean result - true if they 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 relatively complicated.

# Additional Resources

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

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev