Last active
November 3, 2023 01:19
-
-
Save Gerst20051/94a019c1c5146e3ec46047f8a3356e44 to your computer and use it in GitHub Desktop.
Flatten JS Object Keys
This file contains 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) { | |
const result = {}; | |
for (const key of Object.keys(obj)) { | |
if (typeof obj[key] === 'object') { | |
const nested = flatten(obj[key]); | |
for (const nestedKey of Object.keys(nested)) { | |
result[`${key}.${nestedKey}`] = nested[nestedKey]; | |
} | |
} else { | |
result[key] = obj[key]; | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example Input:
Example Output:
const flattenedOutput = flatten(inputObj);