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
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 deepSet(keys, value) { | |
return keys.split('.') | |
.reverse() | |
.reduce((acc, current) => ({ | |
[current]: acc | |
}), value); | |
} | |
//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