Skip to content

Instantly share code, notes, and snippets.

@Quozzo
Last active January 10, 2022 08:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Quozzo/3715ad741cfbbd17065fe5e85d4d62c3 to your computer and use it in GitHub Desktop.
Save Quozzo/3715ad741cfbbd17065fe5e85d4d62c3 to your computer and use it in GitHub Desktop.
Deep spreads objects with a syntax like `Object.assign`
const deepSpread = (...objs: any[]) => {
return objs.reduce(
(mixed, obj = {}) => {
//remove this line to only replace valid indicies instead of the whole array
if (mixed.constructor === Array) mixed = [];
for (const [key, val] of Object.entries(obj)) {
if (
(val && typeof val === 'object') ||
(mixed[key] && typeof mixed[key] === 'object')
)
mixed[key] = deepSpread(mixed[key], val);
else mixed[key] = val;
}
return mixed;
},
objs[1]?.constructor === Array ? [] : objs[0]?.constructor === Array ? [] : {},
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment