Skip to content

Instantly share code, notes, and snippets.

@ryan-haskell
Created March 18, 2018 19:42
Show Gist options
  • Save ryan-haskell/679862b0e3be64cec9e6a44303ab070a to your computer and use it in GitHub Desktop.
Save ryan-haskell/679862b0e3be64cec9e6a44303ab070a to your computer and use it in GitHub Desktop.
Flatten out a nested JSON object.
// Examples
// To make this functions goal more clear, here are some example inputs with their expected outputs.
/*
const examples = [
{
input: { name: 'Ryan' },
output: { name: 'Ryan' }
},
{
input: { name: { first: 'Ryan', last: 'Haskell-Glatz' } },
output: { 'name.first': 'Ryan', 'name.last': 'Haskell-Glatz' }
},
{
input: { name: 'Ryan', age: 24 },
output: { name: 'Ryan', age: 24 }
},
{
input: {
name: { first: 'Ryan', last: 'Haskell-Glatz' },
birthday: { year: 1993, month: 'Nov' }
},
output: {
'name.first': 'Ryan',
'name.last': 'Haskell-Glatz',
'birthday.year': 1993,
'birthday.month': 'Nov'
}
}
]
*/
const isObject = (thing) =>
thing && typeof thing === 'object'
const dottifyWithPrefix = (keyPrefix, obj) =>
Object.keys(obj)
.reduce((kvps, key) => {
const newKvps = isObject(obj[key])
? dottifyWithPrefix(keyPrefix + key, obj[key])
: [ { key: keyPrefix + key, value: obj[key] } ]
return [ ...kvps, ...newKvps ]
}, [])
const kvpsToObject = (obj, { key, value }) => {
obj[key] = value
return obj
}
const dottify = (obj) =>
dottifyWithPrefix('', obj)
.reduce(kvpsToObject, {})
module.exports = dottify
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment