Last active
August 27, 2021 13:06
-
-
Save claudiabdm/38506721dac62f5f78ccaec330af6b42 to your computer and use it in GitHub Desktop.
Flatten JavaScript object using recursion, reduce and spread operator.
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 flattenObject(obj) { | |
| return Object.keys(obj).reduce((newObj, key) => { | |
| const isObject = | |
| typeof obj[key] == "object" && | |
| obj[key] != null && | |
| !Array.isArray(obj[key]) && | |
| Object.keys(obj[key]).length > 0; | |
| if (isObject) { | |
| newObj = { ...newObj, ...flattenObject(obj[key]) }; | |
| } else { | |
| newObj[key] = obj[key]; | |
| } | |
| return newObj; | |
| }, {}); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment