Skip to content

Instantly share code, notes, and snippets.

@daniellizik
Last active January 1, 2016 19:55
Show Gist options
  • Save daniellizik/dcf7878d390abc912192 to your computer and use it in GitHub Desktop.
Save daniellizik/dcf7878d390abc912192 to your computer and use it in GitHub Desktop.
deep search key/value structure and update a value, returning the modified object
/*
var a = {
b: {
c: {
d: false
}
}
};
deepUpdate("b.c.d", true, a) -> a.b.c.d === true
https://jsfiddle.net/h4mvptLb/
*/
function deepUpdate(dir, val, ref) {
return (function loop(arr, val, i, obj, ref) {
if (arr[i + 1])
return loop(arr, val, (i + 1), obj[arr[i]], ref);
if (!arr[i + 1]) {
obj[arr[i]] = val;
return {
obj: ref,
str: JSON.stringify(ref, null, 2)
};
}
})(dir.split("."), val, 0, ref, ref)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment