Compare two json objects in javascript/typescript/Angular

Balaji B
Apr 9, 2021

--

when we have two json objects if we need to check both objects are same or not we can use JSON.stringify but it won’t useful in all the scenarios.

Consider if we have large json object, stringify will fail. In such case it’s better to use following way

ObjectsAreEqual = (Object object1, Object object2) = > {
const objectKeys1 = Object.keys(object1);
const objectKeys2 = Object.keys(object2);
if(objectKeys1.length !== objectKeys2.length) {
return false;
}
for (const key of objectKeys1) {
const value1 = object1[key];
const value2 = object2[key];
const isbothAreObjects = isObject(value1) && isObject(value2);
if((isBothAreObjects && !ObjectsAreEqual(value1, value2)) || (!isBothAreObjects && value1 === value2)) {
return false;
}
}
return true;
}

you can check whether the passed value is Object or not by using below code

isObject = (object) => {
return object !== null && typeof object === 'object';
}

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Balaji B
Balaji B

No responses yet

Write a response