Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Deep Merge and Shallow Merge
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