Skip to content

Instantly share code, notes, and snippets.

@piboistudios
Last active February 4, 2023 00:22
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 piboistudios/96428a11a9fed78ef1a2fbb5acc6724a to your computer and use it in GitHub Desktop.
Save piboistudios/96428a11a9fed78ef1a2fbb5acc6724a to your computer and use it in GitHub Desktop.
An object merge algorithm. Doesn't boast performance at all, but will properly merge nested objects and arrays (by concatenation). This only works if the property is the same type on both objects, otherwise the second object's property will be taken and used to overwrite the target property in the merged object.
module.exports = function merge(a, b) {
return (Object.entries(a).map(e => ({
entries: e,
src: a,
other: b
})).concat(Object.entries(b).map(e => ({
entries: e,
src: b,
other: a
}))
)).reduce((merged, { entries: [key, value], src: a, other: b }) => {
if (!merged[key])
if (value instanceof Array && b[key] instanceof Array) {
merged[key] = [a[key], b[key]].flat();
} else if (value instanceof Object && b[key] instanceof Object) {
merged[key] = merge(value, b[key]);
} else merged[key] = a[key] || b[key];
return merged;
}, {});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment