Last active
February 7, 2017 12:56
-
-
Save jonaslu/99e456e9c8b69496dee74fc2598e7ed4 to your computer and use it in GitHub Desktop.
Deep diffing a js-object ignoring arrays
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
const test1 = { | |
k0: 1, | |
k1: 1, | |
k3: 3, | |
k4: { | |
c: 4 | |
}, | |
k5: { | |
c: 2 | |
} | |
}; | |
const test2 = { | |
k0: 1, | |
k2: 1, | |
k3: 4, | |
k4: { | |
c: 3 | |
}, | |
k5: 5 | |
}; | |
const test3 = { | |
a: { | |
a: { | |
a: { | |
b: 2, | |
c: { | |
a: 1 | |
} | |
} | |
} | |
} | |
}; | |
const test4 = { | |
a: { | |
a: { | |
a: { | |
b: 3, | |
d: { | |
c: 1 | |
} | |
} | |
} | |
} | |
}; | |
function findCommonKeys(a, b) { | |
return Object.keys(a).filter(aKey => b[aKey]); | |
} | |
function findUniqueKeys(a, b) { | |
return Object.keys(a).filter(aKey => !b[aKey]); | |
} | |
function printDiffValue(key, aValue, bValue, prefix) { | |
console.log(`Diffing: ${prefix ? `${prefix}.${key}` : key} avalue`, aValue, 'bvalue', bValue); | |
} | |
function printUniqueKeys(keys, obj, objectPrefix, prefix) { | |
keys.forEach(key => { | |
console.log(`${objectPrefix} Unique: ${prefix ? `${prefix}.${key}` : key}`, 'value', obj[key]); | |
}); | |
} | |
function diff(a, b, diffKey = "") { | |
const aKeys = findUniqueKeys(a,b); | |
const bKeys = findUniqueKeys(b,a); | |
const commonKeys = findCommonKeys(a,b); | |
aKeys && printUniqueKeys(aKeys, a, 'a', diffKey); | |
bKeys && printUniqueKeys(bKeys, b, 'b', diffKey); | |
commonKeys.forEach(key => { | |
const avalue = a[key]; | |
const bvalue = b[key]; | |
if (typeof(avalue) === 'object' && typeof(bvalue) === 'object') { | |
diff(avalue, bvalue, diffKey ? `${diffKey}.${key}` : key); | |
} else if (avalue !== bvalue) { | |
printDiffValue(key, avalue, bvalue, diffKey); | |
} | |
}); | |
} | |
diff(test1, test2); | |
console.log('-----') | |
diff(test1, {}); | |
console.log('-----') | |
diff({}, test2); | |
console.log('-----') | |
diff(test3, test4); | |
console.log('-----') | |
diff(test1, test4); | |
console.log('-----') | |
diff(test2, test4); | |
console.log('-----') | |
diff(test1, test3); | |
console.log('-----') | |
diff(test2, test3); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment