Created
October 8, 2018 03:48
-
-
Save tqwewe/b3fb27fc0d724cb62a58a4244f32e50e to your computer and use it in GitHub Desktop.
Compare two objects (deep)
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
// main.js | |
import objectDifference from './utils/objectDifference' | |
const obj1 = { | |
user: { | |
info: { | |
username: 'foo' | |
} | |
} | |
} | |
const obj2 = { | |
user: { | |
info: { | |
username: 'bar' | |
} | |
} | |
} | |
const objDiff = objectDifference(obj1, obj2) | |
/* | |
objDiff === { | |
user: { | |
info: { | |
username: 'bar' | |
} | |
} | |
} | |
*/ |
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
// objectDifference.js | |
export default (obj1, obj2) => { | |
const compareObjLevel = (obj1, obj2, newObj) => { | |
// Compare current level | |
let newObjChanged = false | |
for (const key in obj2) { | |
// Check if obj1 is different with key | |
if (!obj1.hasOwnProperty(key)) { | |
// If different, add to new object | |
newObj[key] = obj2[key] | |
newObjChanged = true | |
continue | |
} | |
if (typeof obj1[key] !== typeof obj2[key]) { | |
// Different... add to new obj | |
newObj[key] = obj2[key] | |
newObjChanged = true | |
continue | |
} | |
if (typeof obj1[key] === 'object') { | |
newObj[key] = {} | |
const newObjVal = compareObjLevel(obj1[key], obj2[key], newObj[key]) | |
if (newObjVal != null) { | |
newObj[key] = newObjVal | |
newObjChanged = true | |
} else { | |
delete newObj[key] | |
} | |
continue | |
} | |
if (obj1[key] !== obj2[key]) { | |
newObj[key] = obj2[key] | |
newObjChanged = true | |
continue | |
} | |
} | |
// Return different objects in obj2 | |
return newObjChanged ? newObj : null | |
} | |
return compareObjLevel(obj1, obj2, {}) || {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment