Setting a deep JSON property with one call, a answer to a question on StackOverflow that was deleted before I could post it https://stackoverflow.com/questions/47064851/read-or-init-js-variable-to-avoid-cannot-read-property-of-undefined#47064851
function deepSet(keys, defaultValue) { | |
var keyNames = keys.split('.') | |
var out = defaultValue | |
var temp | |
var size = keyNames.length | |
var i | |
for (i = size - 1; i >= 0; i--) { | |
temp = out | |
out = {} | |
out[keyNames[i]] = temp | |
} | |
return out | |
} | |
//You can use it like this: | |
console.log(JSON.stringify(deepSet('foo.name.social.twitter.followers', 100))) | |
//OUTPUTS: | |
//{"foo":{"name":{"social":{"twitter":{"followers":100}}}}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment