Last active
July 27, 2023 18:29
-
-
Save espretto/10ea4f10882fb8b3383cd7da246c86a9 to your computer and use it in GitHub Desktop.
ts: deep merge json serializable 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
function isObject(obj: any) { | |
return typeof obj === "object" && obj !== null; | |
} | |
function isPlainObject(obj: any) { | |
return Object.getPrototypeOf(obj).constructor === Object; | |
} | |
/** | |
* used to deep merge json serializable objects. | |
* skips undefined source values and empty array slots. | |
*/ | |
export function merge(target: any, source: any) { | |
if (isObject(target) && isObject(source)) { | |
if (Array.isArray(source)) { | |
source.forEach((item, i) => (target[i] = merge(target[i], item))); | |
return target; | |
} else if (isPlainObject(source)) { | |
Object.keys(source).forEach( | |
key => (target[key] = merge(target[key], source[key])) | |
); | |
return target; | |
} | |
} | |
return source !== void 0 ? source : target; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment