Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Flatten a nested object to dot notation in JavaScript

125 flatten nested keys to dotted paths, and back

hard

Turn a nested settings object into one flat object keyed by dotted path — shop.address.lga, delivery.zones.1 — and write the inverse. The inverse has to decide at each step whether to create an object or an array, and the only clue is whether the next segment is all digits. Then find the input the scheme cannot represent.

Stuck? Three hints, smallest first
  1. 1. Recursion with an accumulated prefix: at each entry, the path is head ? head + "." + key : key.
  2. 2. An empty object or array has no entries, so a plain recursion drops it. Handle it as its own case or it disappears from the round trip.
  3. 3. When rebuilding, look ahead: if the next segment matches /^\d+$/ the container you are about to create should be an array.

The answer

const isContainer = (v) => v !== null && typeof v === 'object';

const flatten = (value, head = '') => {
  if (!isContainer(value)) return { [head]: value };
  const entries = Object.entries(value);
  if (entries.length === 0) return head ? { [head]: Array.isArray(value) ? [] : {} } : {};
  return entries.reduce((acc, [key, inner]) => {
    const path = head ? `${head}.${key}` : key;
    return { ...acc, ...flatten(inner, path) };
  }, {});
};

const unflatten = (flat) =>
  Object.entries(flat).reduce((root, [path, value]) => {
    const keys = path.split('.');
    const last = keys.pop();
    const parent = keys.reduce((node, key, i) => {
      const nextSegment = keys[i + 1] ?? last;
      if (node[key] === undefined) node[key] = /^\d+$/.test(nextSegment) ? [] : {};
      return node[key];
    }, root);
    parent[last] = value;
    return root;
  }, {});

const settings = {
  shop: { name: 'Balogun Stores', address: { lga: 'Lagos Island', street: 'Broad Street' } },
  delivery: { zones: ['Yaba', 'Surulere'], freeAbove: 500000 },
  open: true,
};

const flat = flatten(settings);
const back = unflatten(flat);
const empties = flatten({ a: {}, b: [] });
const collided = flatten({ 'shop.name': 'typed with a dot', shop: { name: 'nested' } });
const deepArray = unflatten({ 'a.0.b': 1 });

console.log('flat  :', Object.keys(flat));
console.log('back  :', back);
console.log('edges :', empties, collided, deepArray);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('every leaf becomes one dotted key', Object.keys(flat), ['shop.name', 'shop.address.lga', 'shop.address.street', 'delivery.zones.0', 'delivery.zones.1', 'delivery.freeAbove', 'open']);
test('so a value three levels down is one lookup away', flat['shop.address.lga'], 'Lagos Island');
test('an array index is just another segment', flat['delivery.zones.1'], 'Surulere');
test('the round trip rebuilds the original, arrays as arrays', [same(back, settings), Array.isArray(back.delivery.zones)], [true, true]);
test('an empty object or array survives only because it is a special case', empties, { a: {}, b: [] });
test('and it round trips too', same(unflatten(empties), { a: {}, b: [] }), true);
test('a numeric segment makes an array, a name makes an object', [Array.isArray(deepArray.a), deepArray.a[0].b], [true, 1]);
test('a key that already contains a dot collides with a nested one', [Object.keys(collided).length, collided['shop.name']], [1, 'nested']);
test('and a bare value has no path at all, so it lands under the empty key', flatten(5), { '': 5 });

Flattening is how nested configuration meets flat storage: environment variables, form field names, a translation file, a spreadsheet column. The recursion is small because each level only has to know its own prefix, and Object.entries treats an array as keys '0', '1' — which is exactly what makes indices work with no extra code.

The inverse cannot be as clean, because a.0 is ambiguous: an array at index zero, or an object with the key '0'. Looking ahead at the next segment and creating an array when it is all digits is the usual guess, and it is a guess — an object whose keys really are '0' and '1' comes back as an array. The empty container is the other loss: no entries means no leaves, so { a: {} } vanishes unless you write the case for it.

The last two assertions are the honest limits. A dot is a legal character in a key, so { 'shop.name': x } and { shop: { name: y } } flatten to the same path and one silently wins. If your keys can contain dots, the scheme needs an escape or a different separator, and [before, after] arrays of segments beat strings.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.