Skip to content

Instantly share code, notes, and snippets.

@bryandh
Created April 19, 2019 07:28
Show Gist options
  • Save bryandh/96e1d244c0834ec1a53416c47b65c07f to your computer and use it in GitHub Desktop.
Save bryandh/96e1d244c0834ec1a53416c47b65c07f to your computer and use it in GitHub Desktop.
ObjectUtilities including deep merging of multiple objects
export class ObjectUtilities {
public static merge<T extends object = object>(target: T, ...sources: T[]): T {
if (!sources.length)
return target;
const source = sources.shift();
if (source === undefined)
return target;
if (ObjectUtilities.isMergeableObject(target) && ObjectUtilities.isMergeableObject(source))
Object.keys(source).forEach((key: string) => {
if (ObjectUtilities.isMergeableObject(source[key])) {
if (!target[key])
target[key] = {};
ObjectUtilities.merge(target[key], source[key]);
} else
target[key] = source[key];
});
return ObjectUtilities.merge(target, ...sources);
}
public static isObject<T>(item: T): boolean {
return item !== null && typeof item === 'object';
}
private static isMergeableObject<T>(item: T): boolean {
return ObjectUtilities.isObject(item) && !Array.isArray(item);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment