Skip to content

Instantly share code, notes, and snippets.

@kylealwyn
Last active November 14, 2016 17:29
Show Gist options
  • Save kylealwyn/3f703eea9cba6e70e18d77f418167a08 to your computer and use it in GitHub Desktop.
Save kylealwyn/3f703eea9cba6e70e18d77f418167a08 to your computer and use it in GitHub Desktop.
// Only dependency is the lodash library
function deepDiff(oldObj, newObj) {
// Instantiate our changes obj
var changes = {};
// Make sure we are working with objects
oldObj = _(oldObj).value();
newObj = _(newObj).value();
function merge(oldObj, newObj, parent) {
// Attempt to merge old and new objects, and highjack the values in a callback
_.merge(oldObj, newObj, function (oldValue, newValue, key) {
// Make sure we are dealing with different values
if (!_.isEqual(oldValue, newValue)) {
// If current value is an object, we need to set instantiate a new object
// and recurse through the changed object's children
if (_.isObject(newValue)) {
parent[key] = {};
merge(oldValue, newValue, parent[key]);
} else {
// Otherwise we set the value
parent[key] = newValue;
}
}
});
}
// Start it off
merge(oldObj, newObj, changes);
return changes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment