Borislav Hadzhiev
Mon Feb 28 2022·3 min read
Photo by Lê Tân
To compare objects in TypeScript:
JSON.stringify()
to compare objects whose keys are in the same order.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.
type Person = { name: string; age: number; }; const obj1: Person = { name: 'Tom', age: 30, }; const obj2: Person = { name: 'Tom', age: 30, }; if (JSON.stringify(obj1) === JSON.stringify(obj2)) { console.log('✅ objects are equal'); } else { console.log('⛔️ objects are NOT equal'); }
We used the JSON.stringify method to convert the objects to strings and compare the result.
Note that this should only be used if the order of the keys in the two objects
is the same. For example, the following comparison returns false
.
// 👇️ false console.log( JSON.stringify({ age: 30, name: 'Tom' }) === JSON.stringify({ name: 'Tom', age: 30 }) );
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.
type Person = { name: string; age: number; country: string; }; const obj1: Person = { country: 'Chile', name: 'Tom', age: 30, }; const obj2: Person = { age: 30, name: 'Tom', country: 'Chile', }; let areEqual = false; if ( obj1.name === obj2.name && obj1.age === obj2.age && obj1.country === obj2.country ) { areEqual = true; } console.log(areEqual); // 👉️ true
The objects in the example only have a few key-value pairs that we can manually
compare in an if
statement without overcomplicating things.
If your objects do not have nested properties, you can do a relatively simple shallow comparison.
type Person = { name: string; age: number; }; const obj1: Person = { name: 'Tom', age: 30, }; const obj2: Person = { age: 30, name: 'Tom', }; // ✅ 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 first thing we did in our shallow comparison is use the Object.keys method to get an array of the keys of the two objects and check if the two objects have the same number of key-value pairs.
The second comparison we did is - 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 is not met at least
once.
Otherwise, the every
method returns true
and we can conclude that the
shallow equality check passed.
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:
npm i lodash.isequal npm i --save-dev @types/lodash.isequal
Now you can use the library to test the objects for deep equality.
import isEqual from 'lodash.isequal'; type Person = { name: string; age: number; address: { country: string; city: string; }; }; const obj1: Person = { name: 'Tom', age: 30, address: { country: 'Chile', city: 'Santiago', }, }; const obj2: Person = { address: { country: 'Chile', city: 'Santiago', }, age: 30, name: 'Tom', }; console.log(isEqual(obj1, obj2)); // 👉️ true
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.