Flatten an object to dotted paths
Form libraries key errors by "address.postcode". Translation files ship nested but get looked up by dotted key. Both need the nested-to-flat conversion.
Implement flattenObject(source). Walk the object recursively and return a single-level object whose keys are the dotted paths to each leaf and whose values are those leaves. Only plain objects are recursed into. Arrays are leaves and are stored as they are, not indexed into. null is a leaf, even though typeof null is "object". A nested object with no keys of its own is also kept as a leaf under its own path, so { a: {} } flattens to { "a": {} }. Flattening an empty object gives an empty object. Never modify source.
What it has to do
- Join path segments with a dot, producing one entry per leaf.
- Recurse into plain objects only.
- Treat arrays as leaf values rather than indexing into them.
- Treat
nullas a leaf value. - Keep an empty nested object as a leaf under its own path, and return
{}for an empty input.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.