Created
August 14, 2019 18:55
-
-
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 }
This file contains hidden or 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
| /** | |
| * 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