Unflatten dotted keys
A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.
The task
`obj` has dotted keys, like `{ "a.b.c": 1, "a.d": 2 }`, the shape that flattening a nested object produces. Rebuild the nested object: `{ a: { b: { c: 1 }, d: 2 } }`. A key without a dot stays at the top level. Values are kept as they are (an array value stays an array, `undefined` stays `undefined`). Numeric parts like `"k.0"` are still object keys, not array indexes. Keys never conflict (`"a"` and `"a.b"` do not both appear). Do not change `obj`.
What this exercise teaches
Creating an intermediate object only when the key is missing is what lets a.b.c and a.d share the same a. Replacing it on every key throws away what earlier keys built, and turning numeric parts into arrays changes the shape of the result.
A hint if you get stuck
For each key, split on `.`; walk the parts except the last, creating `{}` at each step only when nothing is there yet; then assign the value under the last part.
Try it now, free, no account needed
Every exercise on Scriptdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. The worked solution opens once you solve it or after two tries.
Open this exerciseMore exercises in Data shaping
- CSV text to objectsFree
- Totals per customerFree
- Pivot rows into a lookupFree
- Top N with tiesFree
- Running totalsFree
- Read a nested value by pathFree
- Deep equalityFree
- Flatten a nested objectFree
- Left join two listsFree
- Merge overlapping intervalsFree
- Most frequent valuesFree
- Deep cloneFree
- Flat list to a treeFree
- All orderings of a listFree