Last active
January 10, 2022 08:51
-
-
Save Quozzo/3715ad741cfbbd17065fe5e85d4d62c3 to your computer and use it in GitHub Desktop.
Deep spreads objects with a syntax like `Object.assign`
This file contains 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
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