Skip to content

Instantly share code, notes, and snippets.

@ryan-haskell
Last active February 6, 2018 07:07
Show Gist options
  • Save ryan-haskell/a22e410679993c1c0a6cc7e4f79c3058 to your computer and use it in GitHub Desktop.
Save ryan-haskell/a22e410679993c1c0a6cc7e4f79c3058 to your computer and use it in GitHub Desktop.
Expands out JSON with dots in the property name.
/* Input:
{
"person.name.first": "Ryan",
"person.name.last": "Haskell-Glatz",
"person.age": 23
}
... undottify magic ...
Output:
{
"person": {
"name": {
"first": "Ryan",
"last": "Haskell-Glatz"
},
"age": 24
}
}
*/
const undottify = (obj) =>
Object.keys(obj).reduce((newObj, key) =>
key.split('.').reduceRight((value, key, index, list) => ({
...list.slice(0, index).reduce((value, key) => value[key] || {}, newObj),
[key]: value
}), obj[key])
, {})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment