Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Deep merge two objects in javascript
function mergeObjects(target, source, mergeArrayWith) {
if (!mergeArrayWith) {
mergeArrayWith = (targetArray, sourceArray) => [...targetArray, ...sourceArray];
}
Object.keys(source).forEach(key => {
const existingValue = target[key];
const valueToBeMerged = source[key];
if (Array.isArray(existingValue)) {
if (!Array.isArray(valueToBeMerged)) {
throw Error('type of key ' + key + ' must match in both objects');
}
target[key] = mergeArrayWith(existingValue, valueToBeMerged);
} else if (typeof existingValue === 'object') {
if (typeof valueToBeMerged !== 'object' || Array.isArray(valueToBeMerged)) {
throw Error('type of key ' + key + ' must match in both objects');
}
mergeObjects(existingValue, valueToBeMerged);
} else {
target[key] = valueToBeMerged;
}
});
return target;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment