Last active
February 8, 2017 04:40
-
-
Save AviKav/e0f77e17a88d109ce7affd34f3d5a840 to your computer and use it in GitHub Desktop.
Recursive version of `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
function recursiveAssign(target, ...sources) { | |
for (let i of let objs = Object.keys(sources)) { | |
let obj = sources[objs[i]]; | |
if ((typeof obj !== "object" || obj === null) && obj === sources[sources.length-1]) { | |
// If `sources[objs[i]]` is a a non `Object` built-in and the is (or is the same as) last element in `sources`, then there is no need to go any further. Also, `typeof null === "object"` | |
if (obj === sources[sources.length-1]) { | |
target = obj; | |
return; | |
} | |
} else { | |
for (let j of let fields = Object.keys(sources[objs[i]])) { | |
let field = fields[j]; | |
if (obj[fields[j]] === undefined) {continue;} | |
//No need to make a another function call for a field of a non `Object` | |
recursiveAssign(let target[field] = Object(target[field]), obj[field]); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
for (let...)
for (...in...)