Skip to content

Instantly share code, notes, and snippets.

@SouravDas25
Last active February 12, 2020 05:46
Show Gist options
  • Select an option

  • Save SouravDas25/bcbb57d02ee85abaf6829e26cd88917e to your computer and use it in GitHub Desktop.

Select an option

Save SouravDas25/bcbb57d02ee85abaf6829e26cd88917e to your computer and use it in GitHub Desktop.
Deep Compare 2 Json Object
var a = [
{
"Id": "t.6.C1PRGOO3ZFMACYDJ6H6LFOKCG:C1PRGOO3ZFMACYDJ6H6LFOKCG",
"Version": "4.0",
"GeneratedTime": "Jan 24, 2020 6:57:58 AM",
"IsSecured": false,
"IsRemote": false,
"IsEmbedded": false,
"HasDAC": false,
"IsIndexingEnabled": true,
"HasVariables": {
"Apple": "asdads"
}
},
];
var b = [
{
"Id": "t.6.C1PRGOO3ZFMACYDJ6H6LFOKCG:C1PRGOO3ZFMACYDJ6H6LFOKCG",
"Version": "4.0",
"GeneratedTime": "Jan 24, 2020 6:57:58 AM",
"IsSecured": false,
"IsRemote": false,
"IsEmbedded": false,
"HasDAC": false,
"IsIndexingEnabled": true,
"HasVariables": {
"Applel": "asdads"
}
},
];
PmJson = {
compare : function (obj1, obj2, printFunc, parent) {
//Loop through properties in object 1
var keyNotFound = false;
for (var p in obj1) {
//Check property exists on both objects
if (obj1.hasOwnProperty(p) !== obj2.hasOwnProperty(p)) {
printFunc(`Key not found : "${parent}.${p.toString()}"`);
keyNotFound = true;
continue;
}
switch (typeof (obj1[p])) {
//Deep compare objects
case 'object':
if (!PmJson.compare(obj1[p], obj2[p], printFunc, parent + "." + p.toString())) {
// printFunc(p.toString());
return false;
}
break;
//Compare function code
case 'function':
if (typeof (obj2[p]) == 'undefined' || (p != 'compare' && obj1[p].toString() != obj2[p].toString())) {
// printFunc(p.toString());
return false;
}
break;
//Compare values
default:
if (obj1[p] != obj2[p]) {
printFunc(`Values Changed "${parent}.${p.toString()}" : ${obj1[p]} -> ${obj2[p]}`);
return false;
}
}
}
//Check object 2 for any extra properties
for (var p in obj2) {
if (typeof (obj1[p]) == 'undefined') {
printFunc(`Extra key Found "${parent}.${p.toString()}" `);
}
}
if (keyNotFound) return false;
return true;
}
};
function printFunc(str) {
console.log(str);
};
PmJson.compare(a, b, printFunc, "$");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment