Skip to the code
cf.
+10 XP

#744 Flatten Settings to Dotted Keys

easy

A settings screen stores nested settings but shows them as a flat table, one row per setting, with keys like editor.font.size.

Write flattenKeys(settings) that returns a flat object. Walk the nested objects and arrays; each value that isn't a non-empty object or array is stored under its path, made of the keys (or array indexes) joined with .. Empty objects and empty arrays are stored as values, so they don't disappear. null is a value too.

Example 1

Input: settings = {"editor":{"font":{"size":14},"tabs":[2,4]},"theme":"dark"}
Output: {"editor.font.size":14,"editor.tabs.0":2,"editor.tabs.1":4,"theme":"dark"}

Nested keys are joined with dots, and array items use their index.

Example 2

Input: settings = {"a":{},"b":[],"c":null}
Output: {"a":{},"b":[],"c":null}

Empty containers and null are kept as values.

Constraints

  • settings is a JSON object with at most 10^4 values in total.
  • Keys don't contain ..
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).