Created
February 25, 2019 20:28
-
-
Save ismyrnow/8d7fed53be5f5fc0b22dfb7a12736fed to your computer and use it in GitHub Desktop.
Diff function to compare two objects and return the values for keys that differ
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
import {uniq} from 'lodash'; | |
/** | |
* Shallow compare two objects, returning those props that are different with values from `b`. | |
* @param {*} a | |
* @param {*} b | |
*/ | |
const diff = (a, b) => { | |
if (a === b) { | |
return {}; | |
} | |
if ((a && !b) || (b && !a)) { | |
return b; | |
} else if (!a && !b) { | |
return {}; | |
} | |
const difference = {}; | |
const keys = uniq(Object.keys(a), Object.keys(b)); | |
keys.forEach(key => { | |
if (b[key] !== a[key]) { | |
difference[key] = b[key]; | |
} | |
}); | |
return difference; | |
}; | |
export default diff; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment