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';
}

--

--