Enumerating all object paths in TypeScript

Here’s a small recursive TypeScript function to enumerate all the paths through an object.

E.g. given this object:

{
    "animals": {
        "lion": { 
            "sound": "roar"
        },
        "zebra": { 
            "appearance": "stripes"
        },
        "elephant": {
            "size": "large",
            "features": {
                "trunk": "yes",
                "tusks": "yes",
                "wings": "no"
            },
        },
    },
},

It enumerates these paths:

[
    "animals",
    "animals/lion",
    "animals/zebra",
    "animals/elephant",
    "animals/lion/sound",
    "animals/zebra/appearance",
    "animals/elephant/size",
    "animals/elephant/features",
    "animals/elephant/features/trunk",
    "animals/elephant/features/tusks",
    "animals/elephant/features/wings",
]

The function:

function enumeratePaths(value: any): string[] {
    let paths: string[] = []
    if (value && typeof value === "object") {
        paths = Object.getOwnPropertyNames(value)
        for (const key of Object.getOwnPropertyNames(value)) {
            paths = [
                ...paths,
                ...enumeratePaths(value[key]).map(
                    (subKey) => `${key}/${subKey}`,
                ),
            ]
        }
    }
    return paths
}

View post: Enumerating all object paths in TypeScript