Skip to content

Instantly share code, notes, and snippets.

@AviKav
Last active February 8, 2017 04:40
Show Gist options
  • Save AviKav/e0f77e17a88d109ce7affd34f3d5a840 to your computer and use it in GitHub Desktop.
Save AviKav/e0f77e17a88d109ce7affd34f3d5a840 to your computer and use it in GitHub Desktop.
Recursive version of `Object.assign()`
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]);
}
}
}
}
@AviKav
Copy link
Author

AviKav commented Feb 8, 2017

  1. I forgot to do for (let...)
  2. Thanks to @btipling for alerting me to the inefficiency of for (...in...)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment