Skip to content

Instantly share code, notes, and snippets.

@ericoloewe
Created August 14, 2019 18:55
Show Gist options
  • Select an option

  • Save ericoloewe/2bea284d25e9603ab6a29da397472eb3 to your computer and use it in GitHub Desktop.

Select an option

Save ericoloewe/2bea284d25e9603ab6a29da397472eb3 to your computer and use it in GitHub Desktop.
transform an object to flat object with dots like { 'prop.a.b': value }
/**
* Flat an object
* @param {object} obj
* @param {string|undefined} prevProp
* @returns {object} flatted
*/
function flatObject(obj, prevProp) {
if (typeof obj !== 'object') {
throw new Error('obj must be an object')
}
const mappedProps = Object.keys(obj)
.map(key => {
const nextKey = prevProp != null ? `${prevProp}.${key}` : key
if (typeof obj[key] === 'object') {
return {
isObject: true,
key: key,
value: asd(obj[key], nextKey),
}
}
return {
key: nextKey,
value: JSON.stringify(obj[key]),
}
})
.reduce((p, n) => {
if (n.isObject) {
Object.keys(n.value).forEach(key => {
p[key] = n.value[key]
})
} else {
p[n.key] = n.value
}
return p
}, {})
return mappedProps
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment