Skip to content

Instantly share code, notes, and snippets.

@employee451
Created May 30, 2022 12:01
Show Gist options
  • Save employee451/938ae007cddd9733b64acb9a958428bd to your computer and use it in GitHub Desktop.
Save employee451/938ae007cddd9733b64acb9a958428bd to your computer and use it in GitHub Desktop.
/**
* 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