Skip to content

Instantly share code, notes, and snippets.

@ryannhg
Created Mar 18, 2018
Embed
What would you like to do?
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