Skip to content

Instantly share code, notes, and snippets.

@cedrickring
Created September 19, 2020 20:46
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 cedrickring/562c3ed338e79a91ee4c33af864c3c6c to your computer and use it in GitHub Desktop.
Save cedrickring/562c3ed338e79a91ee4c33af864c3c6c to your computer and use it in GitHub Desktop.
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