Flatten Object
MediumP1Coding
Write flattenObject(obj, depth), which turns a nested object into a single-level object. The key of a nested value is the path of keys joined with a dot.
Rules:
- Only plain objects are flattened. Arrays, strings, numbers, booleans and
nullare leaf values and are kept as they are. - An empty nested object
{}is kept as a leaf value with its dotted key. depthlimits how many levels of nesting are flattened:depth = 0returns a shallow copy,depth = 1flattens objects directly under the top level, and so on. A negativedepthmeans flatten completely.- Do not modify the input. Key order in the result does not matter.
Example 1
- Input
- obj = {"a":1,"b":{"c":2,"d":{"e":3}}}, depth = -1
- Output
- {"a":1,"b.c":2,"b.d.e":3}
Example 2
- Input
- obj = {"a":1,"b":{"c":2,"d":{"e":3}}}, depth = 1
- Output
- {"a":1,"b.c":2,"b.d":{"e":3}}
Example 3
- Input
- obj = {"a":{}}, depth = -1
- Output
- {"a":{}}
Constraints
- The total number of keys is at most 10^4.
- Keys are non-empty strings.
- -1 <= depth <= 1000 (any negative value means unlimited)
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 11. ⌘Enter runs, ⌘⇧Enter submits.