Flatten an Object to Dotted Keys

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code

Write flattenObject(obj), turning a nested plain object into a flat one, as you might for a form, a log line or a settings file. Every value that isn't a plain object or an array goes under its full path, the keys joined with dots, and array items use their position as the key, so a user object holding tags of ["a"] gives the key user.tags.0 with the value "a". Values such as null, numbers, strings and Dates are kept as they are. An empty object or empty array is kept as the value at its own path, so nothing is lost. Return a new object and leave obj unchanged.

Your code must pass

  • Joins nested keys with dots
  • Uses positions for array items
  • Keeps null and other values as they are
  • Keeps empty objects and arrays as values
  • Doesn't change the original object