Is it possible to compare 2 sets of json objects for a difference? What I have is a script thats polling for JSON object via jquery $post(). What I want to do is take the ob
Here is my code:
function getDifferences(oldObj, newObj) {
var diff = {};
for (var k in oldObj) {
if (!(k in newObj)){
diff[k] = undefined; // old key does not exist in new
} else {
switch (typeof oldObj[k]){
case "array": {
String(oldObj[k]) !== String(newObj[k]) ? diff[k] = newObj[k] : null;
break;
} case "object": {
Object.keys(oldObj[k]).forEach(key =>{
if(oldObj[k][key] !== newObj[k][key]){
if(diff[k]){
diff[k][key] = newObj[k][key];
} else {
diff[k] = {[key]: newObj[k][key]}
}
}
});
//JSON.stringify(oldObj[k]) !== JSON.stringify(newObj[k]) ? diff[k] = newObj[k] : null; Optional basic comparision
break;
} default: { //Values are strings or numbers
oldObj[k] !== newObj[k] ? diff[k] = newObj[k] : null;
break;
}
}
}
}
for (k in newObj) {
if (!(k in oldObj))
diff[k] = newObj[k]; // property is new
}
return diff;
}
We get the type of the elements and make an internal comparision of equality.