Last active
November 30, 2016 21:26
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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