Skip to content

Instantly share code, notes, and snippets.

@ismyrnow
Created February 25, 2019 20:28
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 ismyrnow/8d7fed53be5f5fc0b22dfb7a12736fed to your computer and use it in GitHub Desktop.
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
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