Skip to content
Onsite

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 null are leaf values and are kept as they are.
  • An empty nested object {} is kept as a leaf value with its dotted key.
  • depth limits how many levels of nesting are flattened: depth = 0 returns a shallow copy, depth = 1 flattens objects directly under the top level, and so on. A negative depth means 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

Run checks the 3 visible tests, Submit all 11.