Skip to curriculum
Jump to the editor

21.13. Flatten a nested object to dotted keys, and back

Medium
Topics
25–40 min

Many tools only understand one level of keys. Query strings, form field names, .env-style config, translation files, analytics properties and spreadsheet columns all want "address.city" instead of { address: { city } }. Moving data in and out of them means flattening a nested object into dotted keys, and rebuilding the nesting from those keys on the way back.

Write both directions in flatten-object.js. flattenObject(object) returns a one-level object whose keys are dotted paths. unflattenObject(flat) rebuilds the nested object, with arrays where the keys are indexes.

Signature

JAVASCRIPT
function flattenObject(object) // returns { "a.b.0": value, … }
function unflattenObject(flat) // returns the nested object or array
  • object: a plain object or an array. It is not changed.
  • flat: an object whose keys are dotted paths. It is not changed.

Requirements

flattenObject:

  1. Each leaf gets one key: the keys from the top down to it, joined with .. Array indexes are keys too ("list.0"). Holes are skipped.
  2. Only arrays and plain objects are walked. Every other value, including null, undefined, 0, "", Dates and Maps, is a leaf, stored as it is.
  3. An empty object or array (one with no own keys) is stored as a value at its path, as a new {}, or a new array of the same length, so it is not lost. An array of only holes, such as new Array(2), is stored as a new array of length 2.
  4. A top-level array works (its keys start with an index). A top-level value that is not an array or a plain object throws a TypeError.
  5. A key that contains a . throws a TypeError, because it could not be told apart from nesting.
  6. A container that contains itself throws a TypeError. An object used twice (not inside itself) is flattened at both paths.
  7. An own key named __proto__ becomes an ordinary key of the result; it never changes the result's prototype.

unflattenObject:

  1. Each key is split at ., and the value is placed at that path, creating the levels on the way.
  2. A level becomes an array when it has at least one key and every key it has is an index ("0", or digits without a leading zero). Missing indexes become holes. Any other level, including the top, is an ordinary object.
  3. A path that needs a value to be an object ("a" and "a.b" both present, in either order) throws a TypeError.
  4. A key part equal to __proto__, constructor or prototype throws a TypeError, and nothing reaches Object.prototype.
  5. Values are placed as they are, so {} and [] values come back as empty containers. The result is made of ordinary objects and arrays.

Both:

  1. unflattenObject(flattenObject(x)) equals x, holes and lengths included, for any x whose keys have no dots and none of the three blocked names, and whose objects do not have only index keys, with three exceptions the format cannot record: an array whose last slot is a hole after at least one item ([1, , ] comes back as [1]), a top-level array with no items ([] or new Array(2) flattens to {} and comes back as {}), and an array with a named field (an array [1] with label: "x" flattens to "a.0" and "a.label", the same keys as the object { 0: 1, label: "x" }, and comes back as that object; "01" counts as a name, not an index).

Examples

JAVASCRIPT
flattenObject({ user: { name: "Ada", tags: ["a", "b"] }, prefs: {} });
// { "user.name": "Ada", "user.tags.0": "a", "user.tags.1": "b", prefs: {} }
JAVASCRIPT
unflattenObject({ "user.name": "Ada", "user.tags.0": "a", "user.tags.1": "b", prefs: {} });
// { user: { name: "Ada", tags: ["a", "b"] }, prefs: {} }
JAVASCRIPT
unflattenObject({ "a.0": 1, "a.x": 2 }); // { a: { 0: 1, x: 2 } }  (not every key is an index)
unflattenObject({ a: 1, "a.b": 2 });     // throws TypeError
flattenObject({ "v1.2": true });         // throws TypeError

Environment

  • Plain JavaScript in a browser page; the tests call the globals flattenObject and unflattenObject from flatten-object.js.
  • Only own, enumerable string keys are used (Object.keys). Symbol keys are out of scope.
  • An object whose keys are all indexes (such as { 0: "a" }) comes back as an array: that is a known limit of the dotted format, not a bug.

Hints

  1. In unflattenObject, can you tell whether a level is an array before you have seen all of its keys?
  2. How can you tell a level you created apart from a value that happens to be an object?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…