Last active
January 1, 2016 19:55
-
-
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
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
/* | |
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