Skip to content

Instantly share code, notes, and snippets.

@Ustice
Last active November 30, 2016 21:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ustice/be6aa0365fcf0b1579d5a9d3ea24970e to your computer and use it in GitHub Desktop.
Save Ustice/be6aa0365fcf0b1579d5a9d3ea24970e to your computer and use it in GitHub Desktop.
Compares the properties of two objects and returns an array of paths to the properties of the baseObject that are different or nonexistent in the compareObject.
/**
* Compares the properties of two objects and returns an array of paths to the
* properties of the baseObject that are different or non-existant in the
* compareObject.
*
* person0 = {
* name: {
* first: 'Eve'
* }
* };
*
* person0 = {
* name: {
* first: 'Jim'
* }
* };
*
* collectDifferentProperties(1,1); // []
* collectDifferentProperties(1,2); // [""]
* collectDifferentProperties(person0, person1); // ["name.first"]
*/
function getDifferentProperties (baseObject, compareObject, ancestors, accumulator) {
accumulator = accumulator || [];
ancestors = ancestors || [];
let isBaseAnObject = typeof baseObject === 'object' && !!baseObject;
let areObjectsTheSameType = typeof baseObject === typeof compareObject;
let isBaseAFunction = typeof baseObject === 'function';
if (isBaseAnObject && areObjectsTheSameType) {
Object.keys(baseObject).forEach(key => {
let path = ancestors.concat(key);
let value = baseObject[key];
if (!baseObject.hasOwnProperty(key)) {
return;
}
getDifferentProperties(baseObject[key], compareObject[key], path, accumulator);
});
} else if (!areObjectsTheSameType || !isBaseAFunction && baseObject != compareObject) {
accumulator.push(ancestors.join('.'));
}
return accumulator;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment