AniUI Academy

Rebuild an object from dotted paths

hardArrays & Objects+350 XPPractice

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.

Arguments

flatObject<string, any>
A single-level object whose keys are dot-separated paths.

Returns

Object — The nested structure the paths describe. Numeric segments produce arrays; everything else produces plain objects.

Examples

unflatten({ "a.b.c": 1, d: 2 });
// { a: { b: { c: 1 } }, d: 2 }
unflatten({ "list.0": "x", "list.1": "y" });
// { list: ["x", "y"] } — integer segments produce an array

unflatten({ "rows.0.id": 7, "rows.0.name": "Ada" });
// { rows: [{ id: 7, name: "Ada" }] } — objects inside arrays

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.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +350 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.