Created
April 19, 2019 07:28
-
-
Save bryandh/96e1d244c0834ec1a53416c47b65c07f to your computer and use it in GitHub Desktop.
ObjectUtilities including deep merging of multiple objects
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
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