Last active
January 11, 2020 00:07
-
-
Save hrishikeshs/ddf8bc17c9e663cc91950af35804847f to your computer and use it in GitHub Desktop.
diff two objects and return values/path which are different, null if there is no diff.
This file contains hidden or 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
function diffObjects(x, y) { | |
if (x === y) return null; | |
if (x !== x) return y !== y ? null : y; | |
if (typeof x !== typeof y) return y; | |
if (typeof x !== 'object') return y; | |
var typeX = getType(x); | |
var typeY = getType(y); | |
if (typeX !== typeY) return y; | |
if (typeX === 'date' ) return +x === +y ? null : y; | |
if (typeX === 'array' ) return deepDiffArray(x, y); | |
if (typeX === 'object') return deepDiffObjects(x, y); | |
return y; | |
} | |
function deepDiffArray(x, y) { | |
return x.find((xx, i) => diffObjects(xx, y[i]) !== null) || null; | |
} | |
function getType(x) { | |
var type = Object.prototype.toString.call(x); | |
return type.substring(8, type.length - 1 ).toLowerCase(); | |
} | |
function deepDiffObjects(x, y) { | |
var keysX = Object.keys(x); | |
var keysY = Object.keys(y); | |
const diff1 = deepDiffArray(keysX.sort(), keysY.sort()); | |
return diff1 ? diff1 : deepCompareObjects(x, y); | |
} | |
function deepCompareObjects(x, y) { | |
var keysX = Object.keys(x); | |
const diff = keysX.find(k => { | |
return diffObjects(x[k], y[k]) !== null; | |
}); | |
return diff ? diff + '.' + diffObjects(x[diff], y[diff]) : null; | |
} | |
var actual = { | |
foo: 'nar', | |
nested: { | |
thing: { | |
foobarbaz: 'stu5ff', | |
}, | |
bar: { | |
biz: '111' | |
} | |
}, | |
}; | |
var requiredProps = { | |
foo: 'nar', | |
nested: { | |
thing: { | |
foobar: 'stuff', | |
}, | |
bar: { | |
biz: '111' | |
} | |
}, | |
}; | |
console.log(deepDiffObjects(actual, requiredProps)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment