21.13. Flatten a nested object to dotted keys, and back
Topics
This question is in
21. Recursion and nested dataMany 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
function flattenObject(object) // returns { "a.b.0": value, … }
function unflattenObject(flat) // returns the nested object or arrayobject: a plain object or an array. It is not changed.flat: an object whose keys are dotted paths. It is not changed.
Requirements
flattenObject:
- 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. - Only arrays and plain objects are walked. Every other value, including
null,undefined,0,"", Dates and Maps, is a leaf, stored as it is. - 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 asnew Array(2), is stored as a new array of length 2. - 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. - A key that contains a
.throws aTypeError, because it could not be told apart from nesting. - A container that contains itself throws a
TypeError. An object used twice (not inside itself) is flattened at both paths. - An own key named
__proto__becomes an ordinary key of the result; it never changes the result's prototype.
unflattenObject:
- Each key is split at
., and the value is placed at that path, creating the levels on the way. - 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. - A path that needs a value to be an object (
"a"and"a.b"both present, in either order) throws aTypeError. - A key part equal to
__proto__,constructororprototypethrows aTypeError, and nothing reachesObject.prototype. - Values are placed as they are, so
{}and[]values come back as empty containers. The result is made of ordinary objects and arrays.
Both:
unflattenObject(flattenObject(x))equalsx, holes and lengths included, for anyxwhose 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 ([]ornew Array(2)flattens to{}and comes back as{}), and an array with a named field (an array[1]withlabel: "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
flattenObject({ user: { name: "Ada", tags: ["a", "b"] }, prefs: {} });
// { "user.name": "Ada", "user.tags.0": "a", "user.tags.1": "b", prefs: {} }unflattenObject({ "user.name": "Ada", "user.tags.0": "a", "user.tags.1": "b", prefs: {} });
// { user: { name: "Ada", tags: ["a", "b"] }, prefs: {} }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 TypeErrorEnvironment
- Plain JavaScript in a browser page; the tests call the globals
flattenObjectandunflattenObjectfromflatten-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
- In
unflattenObject, can you tell whether a level is an array before you have seen all of its keys? - 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