Skip to content

Instantly share code, notes, and snippets.

@tqwewe
Created October 8, 2018 03:48
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 tqwewe/b3fb27fc0d724cb62a58a4244f32e50e to your computer and use it in GitHub Desktop.
Save tqwewe/b3fb27fc0d724cb62a58a4244f32e50e to your computer and use it in GitHub Desktop.
Compare two objects (deep)
// 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'
}
}
}
*/
// 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