Skip to content

Instantly share code, notes, and snippets.

@blackavec
Created August 10, 2018 06:27
Show Gist options
  • Save blackavec/10893846c9c7d9550a60bd7a4014caa4 to your computer and use it in GitHub Desktop.
Save blackavec/10893846c9c7d9550a60bd7a4014caa4 to your computer and use it in GitHub Desktop.
get a diff from 2 objects(Recursively)
function objectDiff (object, newObject, exclude) {
const result = {}
if (!exclude) {
exclude = []
}
for (const prop in newObject) {
if (newObject.hasOwnProperty(prop) && prop != '__proto__' && exclude.indexOf(newObject[prop]) == -1) {
if (
// consider a diff if object didn't have the prop
!object.hasOwnProperty(prop) ||
// consider a diff if array didn't match between object and updated one
(object[prop].length !== newObject[prop].length && typeof newObject[prop] === 'object')
) {
result[prop] = newObject[prop]
} else if (newObject[prop] === Object(newObject[prop])) {
const difference = objectDiff(newObject[prop], object[prop])
if (Object.keys(difference).length > 0) result[prop] = difference
} else if (newObject[prop] !== object[prop]) {
if (newObject[prop] === undefined) {
result[prop] = 'undefined'
}
if (newObject[prop] === null) {
result[prop] = undefined
} else if (typeof newObject[prop] === 'function') {
result[prop] = 'function'
} else if (typeof newObject[prop] === 'object') {
result[prop] = 'object'
} else {
result[prop] = newObject[prop]
}
}
}
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment