Skip to the code
cf.
+25 XP

#746 Rebuild Nested Settings

medium

Environment variables and form fields often arrive flat, with keys like db.host and db.port. Turn them back into nested objects.

Write unflatten(flat) where flat maps dotted keys to values. Split each key on . and create nested plain objects along the path (never arrays, even for numeric parts), storing the value at the last part. No key is both a value and a prefix of another key.

Example 1

Input: flat = {"db.host":"localhost","db.port":5432,"debug":true}
Output: {"db":{"host":"localhost","port":5432},"debug":true}

db.host and db.port share the db object.

Example 2

Input: flat = {"a.0":"x","a.1":"y"}
Output: {"a":{"0":"x","1":"y"}}

Numeric parts still create objects, not arrays.

Constraints

  • flat has at most 10^4 keys; each key has 1 to 20 non-empty parts.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).