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.
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 arraysWhat 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.
- 1.rebuilds nested objects
- 2.creates an array for integer segments
- 3.merges keys sharing a prefix
- 4.nests objects inside arrays
- 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.