Created
May 30, 2022 12:01
-
-
Save employee451/938ae007cddd9733b64acb9a958428bd to your computer and use it in GitHub Desktop.
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
/** | |
* Returns an array with the names of the keys of an object. | |
* Supports nested objects. | |
* | |
* @example | |
* getObjectKeyNames({ | |
* some: { | |
* nested: { | |
* value: 'string' | |
* } | |
* }, | |
* normalValue: 'string' | |
* }) | |
* | |
* Returns: ['some.nested.value', 'normalValue'] | |
*/ | |
export const getNestedObjectKeyNames = ( | |
object: Record<string, any> | |
): string[] => { | |
let keyNames: string[] = [] | |
for (const key in object) { | |
// If the value for the key is an object, repeat the process for that nested object | |
if (typeof object[key] === 'object') { | |
const nestedKeyNames = getNestedObjectKeyNames(object[key]).map( | |
(nestedKey) => `${key}.${nestedKey}` | |
) | |
keyNames = [...keyNames, ...nestedKeyNames] | |
} else { | |
keyNames.push(key) | |
} | |
} | |
return keyNames | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment