Created
June 15, 2018 05:30
-
-
Save aire-con-gas/016c7b46421b5e633ba4a531b3c8ccd3 to your computer and use it in GitHub Desktop.
Flatten nested object
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
| function flatten(obj, key_id = '') { | |
| let newObj = {}; | |
| const keyPrefix = key_id + (key_id !== '' ? '.' : ''); | |
| for(let key in obj) { | |
| if (typeof obj[key] === 'object') { | |
| newObj = Object.assign({}, newObj, flatten(obj[key], key)); | |
| } else { | |
| newObj[keyPrefix + key] = obj[key]; | |
| } | |
| } | |
| return newObj; | |
| } | |
| const start = { | |
| a: 'b', | |
| c: { | |
| d: 'e', | |
| f: 'g', | |
| h: { | |
| i: 'j', | |
| k: 'l', | |
| m: { | |
| n: 'o' | |
| } | |
| } | |
| }, | |
| p: 'q' | |
| }; | |
| console.log('flatten', flatten(start)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment