Last active
October 3, 2021 14:22
-
-
Save rszamszur/f94648338aa7901467f41d2583fd90b4 to your computer and use it in GitHub Desktop.
Recursive shallow copy
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 recursiveShallowCopy(target, source) { | |
const isObject = (obj) => obj && typeof obj === 'object'; | |
if (!isObject(target) || !isObject(source)) { | |
return source; | |
} | |
for (const [key, value] of Object.entries(source)) { | |
if (Array.isArray(value)) { | |
target[key] = recursiveShallowCopy([], value) | |
} else if (isObject(value)) { | |
target[key] = recursiveShallowCopy({}, value); | |
} else { | |
target[key] = value; | |
} | |
} | |
return target; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment