Deep Merge and Shallow Merge
This file contains 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
export const shallowMerge = <T extends object = Record<string, any>>( | |
...objects: T[] | |
): T => { | |
return objects.reduce((prev, cur) => ({ ...prev, ...cur }), {} as T); | |
}; | |
export const deepMerge = <T extends object = Record<string, any>>( | |
target: T, | |
...sources: object[] | |
): T => { | |
const merge = (target: object, source: object) => { | |
Object.keys(source).forEach((key: string) => { | |
const targetValue = target[key]; | |
const sourceValue = source[key]; | |
if (Array.isArray(targetValue) && Array.isArray(sourceValue)) { | |
target[key] = targetValue.concat(sourceValue); | |
} else if (is.object(targetValue) && is.object(sourceValue)) { | |
target[key] = merge(Object.assign({}, targetValue), sourceValue); | |
} else { | |
target[key] = sourceValue; | |
} | |
}); | |
return target; | |
}; | |
return sources.reduce((prev, cur) => merge(prev, cur), target) as T; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment