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.
Code
// 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: trueWhat 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. The file defines `flattenObject`, `unflatten` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.