Unflatten Dotted Keys
Form libraries often submit fields as flat keys such as "address.city" or "items.0.qty". Turn such a flat object back into a nested one.
Split every key on .. Walk the path from the top-level object, creating containers as needed: when a container must be created for the next segment, it is an array if that next segment is a non-negative integer written without leading zeros (0, 7, 12 but not 01), and a plain object otherwise. The last segment receives the value. The top level is always an object.
The input never contains conflicting keys (a path is never both a value and a container), and array indexes for each array are exactly 0 to n-1, though not necessarily in order.
Example 1
Input: flat = {"a.b":1,"a.c":2,"d":3} Output: {"a":{"b":1,"c":2},"d":3} Explanation: Two levels of objects.
Example 2
Input: flat = {"users.0.name":"A","users.1.name":"B","users.0.age":30} Output: {"users":[{"name":"A","age":30},{"name":"B"}]} Explanation: The `0` and `1` segments create an array of users.
Constraints
- 0 <= number of keys <= 10^4
- Each key has 1 to 20 non-empty segments
Hint 1
Look one segment ahead to decide between [] and {}.
Hint 2
A regex like /^(0|[1-9]\d*)$/ recognises an index.
Discussion 0
Join free to post in the discussion.
Good practice for: Frontend Developer, Full Stack Developer, Mobile App Developer, Automation Test Engineer, Backend Developer
Run checks your code on 3 sample tests. Submit runs all 8 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.