Flatten Object To Dotted Paths

Recursively walk nested objects into dotted key paths and rebuild the tree with unflatten, with arrays kept as leaf values.

JavascriptConfig Management

Code

snippet
// Flatten nested objects into dotted key paths; arrays stay leaf values
function flattenObject(value, prefix, out) {
  prefix = prefix || '';
  out = out || {};
  for (const key of Object.keys(value)) {
    const path = prefix ? prefix + '.' + key : key;
    const item = value[key];
    if (item && typeof item === 'object' && !Array.isArray(item)) {
      flattenObject(item, path, out);
    } else {
      out[path] = item;
    }
  }
  return out;
}

function unflatten(flat) {
  const nested = {};
  for (const path of Object.keys(flat)) {
    const keys = path.split('.');
    let cursor = nested;
    for (const key of keys.slice(0, -1)) {
      cursor[key] = cursor[key] || {};
      cursor = cursor[key];
    }
    cursor[keys[keys.length - 1]] = flat[path];
  }
  return nested;
}

const config = { server: { host: 'localhost', tls: { enabled: true } }, port: 8080 };
const flat = flattenObject(config);
console.log('flat:', flat);
console.log('arrays stay leaves:', flattenObject({ tags: ['a', 'b'] }));
console.log('round trip equal:', JSON.stringify(unflatten(flat)) === JSON.stringify(config));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

flat: { 'server.host': 'localhost', 'server.tls.enabled': true, port: 8080 }
arrays stay leaves: { tags: [ 'a', 'b' ] }
round trip equal: true

What the file does

The code’s whole job belongs to the functions flattenObject and unflatten.

The core work runs in nested loops — outer for (const key of Object.keys(value)), inner for (const path of Object.keys(flat)).

Watch out for

  • No third-party code is loaded at any point while this runs.

Applying it

The method shape you reuse: function flattenObject(value, prefix, out)

The run emits 3 labeled sections — flat:, arrays stay leaves:, round trip equal: — one per step.

Statements that matter

const config = { server: { host: 'localhost', tls: { enabled: true } }, port: 8080 };
const path = prefix ? prefix + '.' + key : key;
cursor[keys[keys.length - 1]] = flat[path];

Interactive Tools for This Topic

FAQ

Any setup needed beyond the language runtime?
None — the language runtime is the only requirement. The file defines `flattenObject`, `unflatten` at load time.