Diff 2 objects
get difference between two objects
by slawe
JavaScript
function findDifferences(objectA, objectB) {
var propertyChanges = [];
var objectGraphPath = [];
(function callee(a, b) {
if(a.constructor == Array) {
// BIG assumptions here: That both arrays are same length, that
// the members of those arrays are _essentially_ the same, and
// that those array members are in the same order...
for(var i = 0; i < a.length; i++) {
objectGraphPath.push("[" + i.toString() + "]");
callee(a[i], b[i]);
objectGraphPath.pop();
}
} else if(a.constructor == Object || (a.constructor != Number &&
a.constructor != String && a.constructor != Date &&
a.constructor != RegExp && a.constructor != Function &&
a.constructor != Boolean)) {
// we can safely assume that the objects have the
// same property lists, else why compare them?
for(var property in a) {
objectGraphPath.push((property));
if(a[property].constructor != Function) {
callee(a[property], b[property]);
}
objectGraphPath.pop();
}
} else if(a.constructor != Function) { // filter out functions
if(a != b) {
propertyChanges.push({ "property": objectGraphPath.join(""), "oldValue": a, "newValue": b });
}
}
})(objectA, objectB);
return propertyChanges;
}
var one = {
generatedName: 'some namee',
includeModule: true,
odometer: [0, 170],
states: ['AE', 'LA', 'NY']
}, two = {
generatedName: 'some name',
includeModule: true,
odometer: [0, 160],
states: ['AE', 'LA', 'NY']
};
console.log(findDifferences(one, two));