Rebuild an object from dotted paths
Form libraries track fields under dotted names. Before you POST, that flat bag of "user.address.city" keys has to become the nested body the API expects.
Implement unflatten(flat), the inverse of flattening. flat is a single-level object whose keys are dot-separated paths. Build and return the nested structure they describe. A segment that is a non-negative integer written without a leading zero — "0", "1", "12" — means the container it indexes is an array; any other segment means a plain object. Keys that share a prefix merge into the same container, so "a.b" and "a.c" both end up inside one a object. The root is always a plain object. An empty input returns an empty object.
What it has to do
- Split each key on dots and create the containers the path describes.
- Create an array when the next segment is a non-negative integer, and a plain object otherwise.
- Merge keys that share a prefix into the same container.
- Always return a plain object at the root.
- 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.