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.
Arguments
sourceObject- The nested object to flatten. Not modified.
Returns
Object<string, any> — A single-level object whose keys are dot-separated paths to each leaf and whose values are those leaves.
Examples
flattenObject({ a: { b: { c: 1 } }, d: 2 });
// { "a.b.c": 1, d: 2 }flattenObject({ tags: [1, 2], meta: { ok: true } });
// { tags: [1, 2], "meta.ok": true } — arrays are leaves, not indexed
flattenObject({ a: {} });
// { a: {} } — an empty nested object survives as its own leafWhat 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.
Stuck? The javascript course covers everything this challenge needs.
- 1.joins nested keys with dots
- 2.treats arrays as leaves
- 3.treats null as a leaf
- 4.keeps an empty nested object as a leaf
- 5.returns an empty object for an empty input
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.