Created
March 18, 2018 19:42
-
-
Save ryan-haskell/679862b0e3be64cec9e6a44303ab070a to your computer and use it in GitHub Desktop.
Flatten out a nested JSON object.
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
// 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