Last active
February 4, 2023 00:22
-
-
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.
This file contains hidden or 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
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