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