Created
May 4, 2020 15:18
-
-
Save lhr0909/e36bb137f437dc368c3dd8a3d62f971e to your computer and use it in GitHub Desktop.
Flatten a JSON object in TypeScript / JavaScript
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
| import _ from 'lodash'; | |
| function flattenObject(obj: any): any { | |
| function _flattenPairs(obj: any, prefix: string): [string, any][] { | |
| // console.log(obj, prefix); | |
| if (!_.isObject(obj)) { | |
| return [prefix, obj]; | |
| } | |
| return _.toPairs(obj).reduce((final: [string, any][], nPair: [string, any]) => { | |
| const flattened = _flattenPairs(nPair[1], `${prefix}.${nPair[0]}`); | |
| if (flattened.length === 2 && !_.isObject(flattened[0]) && !_.isObject(flattened[1])) { | |
| return final.concat([flattened as [string, any]]); | |
| } else { | |
| return final.concat(flattened); | |
| } | |
| }, []); | |
| } | |
| if (!_.isObject(obj)) { | |
| return JSON.stringify(obj); | |
| } | |
| const pairs: [string, any][] = _.toPairs(obj).reduce((final: [string, any][], pair: [string, any]) => { | |
| const flattened = _flattenPairs(pair[1], pair[0]); | |
| if (flattened.length === 2 && !_.isObject(flattened[0]) && !_.isObject(flattened[1])) { | |
| return final.concat([flattened as [string, any]]); | |
| } else { | |
| return final.concat(flattened); | |
| } | |
| }, []); | |
| return pairs.reduce((acc: any, pair: [string, any]) => { | |
| acc[pair[0]] = pair[1]; | |
| return acc; | |
| }, {}); | |
| } | |
| console.log(JSON.stringify(flattenObject({ | |
| a: { | |
| b: { | |
| c: 'd' | |
| }, | |
| e: 'f' | |
| }, | |
| g: 'h' | |
| }), null, 2)); | |
| /* | |
| prints: | |
| { | |
| "a.b.c": "d", | |
| "a.e": "f", | |
| "g": "h" | |
| } | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment