Skip to content

Instantly share code, notes, and snippets.

@espretto
Last active July 27, 2023 18:29
Show Gist options
  • Save espretto/10ea4f10882fb8b3383cd7da246c86a9 to your computer and use it in GitHub Desktop.
Save espretto/10ea4f10882fb8b3383cd7da246c86a9 to your computer and use it in GitHub Desktop.
ts: deep merge json serializable objects
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