Skip to content

Instantly share code, notes, and snippets.

@kig
Created May 3, 2022 01:10
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 kig/2470596b7d56c862e0932fb715e547fa to your computer and use it in GitHub Desktop.
Save kig/2470596b7d56c862e0932fb715e547fa to your computer and use it in GitHub Desktop.
JS Object diff function
const objDiff = (a, b) => {
if (typeof a === typeof b && typeof a === 'object') {
const diff = {};
let changed = false;
for (let i in a) {
if (!b.hasOwnProperty(i)) {
diff[i] = 'DELETED';
changed = true;
continue;
}
const d = objDiff(a[i], b[i]);
if (d !== undefined) {
diff[i] = d;
changed = true;
}
}
for (let i in b) {
if (!a.hasOwnProperty(i)) {
diff[i] = b[i];
changed = true;
}
}
if (changed) return diff;
} else if (a !== b) return b;
return undefined;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment