← Back to JavaScript, page 6

javascript-0102 · Medium mid

How do you flatten a nested object into dot-notation keys and turn it back again?

Walk the object recursively, passing down the key path, and write each leaf value into a flat result under the joined path. Decide how to treat arrays, empty objects, and keys that contain the separator. To reverse it, split each key and create nested objects or arrays along the path, and block keys such as __proto__.

Full answer

Flattening turns { a: { b: 1 } } into { 'a.b': 1 }. It is used for form data, query strings, translation files, and logging. The core is a recursive function with a prefix. For each own key, build the path (prefix + '.' + key). If the value is a plain object or an array with content, recurse. Otherwise it is a leaf and you store it under the path.

Decisions to state out loud:

  • Arrays: use the index as the key (items.0), so the structure can be restored.
  • Empty objects and arrays: keep them as leaf values, otherwise the keys vanish and cannot be restored.
  • Dates and other class instances: treat anything that is not a plain object or array as a leaf.
  • Keys that already contain the separator: they make the result ambiguous. Choose another separator or escape it.
  • Cycles: this simple version would recurse forever, so mention a seen set if cycles are possible.

Unflattening reads each key, splits it by the separator, and walks down the result object, creating containers as needed. When the next part of the path is a number, create an array, otherwise an object. Finally assign the value at the last part. A security point matters here: if the input keys come from users, a key like __proto__.polluted would write to Object.prototype. Reject __proto__, constructor, and prototype parts, or build the result with Object.create(null).

Complexity is linear in the number of leaves, plus the cost of building the path strings.

javascript
const isPlainObject = (value) =>
  value !== null && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype;

function flatten(input, separator = '.', prefix = '', out = {}) {
  for (const key of Object.keys(input)) {
    const path = prefix ? prefix + separator + key : key;
    const value = input[key];
    const container = isPlainObject(value) || Array.isArray(value);
    if (container && Object.keys(value).length > 0) {
      flatten(value, separator, path, out);
    } else {
      out[path] = value;
    }
  }
  return out;
}

const UNSAFE = new Set(['__proto__', 'constructor', 'prototype']);

function unflatten(flat, separator = '.') {
  const result = {};
  for (const [path, value] of Object.entries(flat)) {
    const parts = path.split(separator);
    if (parts.some((part) => UNSAFE.has(part))) continue;
    let node = result;
    parts.forEach((part, index) => {
      if (index === parts.length - 1) {
        node[part] = value;
        return;
      }
      if (!Object.hasOwn(node, part)) {
        node[part] = /^\d+$/.test(parts[index + 1]) ? [] : {};
      }
      node = node[part];
    });
  }
  return result;
}

const data = {
  user: { name: 'Asha', tags: ['a', 'b'], address: { city: 'Pune', geo: {} } },
  active: true,
  created: new Date(0),
  empty: [],
};

const flat = flatten(data);
console.log(flat);
console.log(unflatten(flat));
console.log('round trip equal:', JSON.stringify(unflatten(flat)) === JSON.stringify(data));
console.log(flatten({ a: { b: 1 } }, '/'));
const attack = unflatten({ '__proto__.polluted': 'yes', 'safe.key': 1 });
console.log(attack, ({}).polluted);

Run with Node.js v24.22.1 as js-102.js; two runs gave identical output. Output: { 'user.name': 'Asha', 'user.tags.0': 'a', 'user.tags.1': 'b', 'user.address.city': 'Pune', 'user.address.geo': {}, active: true, created: 1970-01-01T00:00:00.000Z, empty: [] } { user: { name: 'Asha', tags: [ 'a', 'b' ], address: { city: 'Pune', geo: {} } }, active: true, created: 1970-01-01T00:00:00.000Z, empty: [] } round trip equal: true { 'a/b': 1 } { safe: { key: 1 } } undefined

Key points

  • Recurse with a path prefix and store leaves under the joined key.
  • Use indexes for arrays and keep empty objects and arrays as leaves.
  • Treat only plain objects and arrays as containers.
  • Unflatten by splitting keys and creating arrays for numeric parts.
  • Block __proto__, constructor, and prototype when unflattening untrusted keys.

Common mistakes

  • Dropping empty objects and arrays, so they disappear after a round trip.
  • Recursing into Date or class instances and producing nonsense keys.
  • Unflattening user keys without blocking __proto__.
  • Using a separator that appears inside real keys.

Follow-ups

  • How would you handle keys that contain the separator?
  • How would you support cycles in flatten?
  • How would you write the same function with an iterative stack instead of recursion?

Tips

  • State the rule for arrays and empty values before coding.
  • Mention the prototype pollution risk when unflattening input.
  • Give the complexity: linear in the number of leaves.