Skip to content

Instantly share code, notes, and snippets.

@jasonsperske
Last active November 9, 2021 17:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonsperske/4ed039c06acc15af82f2d990bef6a004 to your computer and use it in GitHub Desktop.
Save jasonsperske/4ed039c06acc15af82f2d990bef6a004 to your computer and use it in GitHub Desktop.
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, 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