Expand dotted keys into nested objects and arrays, with escapes
Form libraries and spreadsheet importers often hand you flat records whose keys describe where each value belongs, such as 'shipping.address.city' or 'items.0.sku'. Before you can send them to an API, you need the nested shape back. Implement expandKeys(flat), which turns a flat object with dotted keys into a nested object.
expandKeys(flat) // => nested plain object
. into segments. Keys never contain empty segments (no 'a..b', leading or trailing dots).\.) escapes it: the dot belongs to the segment. In JavaScript source that is written 'a\\.b'. A backslash before any other character is kept as is.'0' or a positive integer without leading zeros ('7', '12'; not '01' or '-1').TypeError.Object.keys order. Arrays can end up with holes, for example from 'slots.2' alone.TypeError: a key whose path runs through a value stored by another key ('a' and 'a.b', in either order), or two keys that end at the same place.__proto__, constructor, or prototype segment, so a crafted key cannot reach shared prototypes.flat or any value in it.expandKeys({ 'app.name': 'Pix', 'app.theme.mode': 'dark', debug: false });
// => { app: { name: 'Pix', theme: { mode: 'dark' } }, debug: false }
expandKeys({ 'users.0.name': 'Ana', 'users.1.name': 'Bo', 'users.0.admin': true });
// => { users: [{ name: 'Ana', admin: true }, { name: 'Bo' }] }
expandKeys({ 'versions.01': 'x', 'versions.1': 'y' });
// => { versions: { '01': 'x', '1': 'y' } } ('01' is not an index, so versions is an object)
expandKeys({ 'meta.og\\.title': 'Hello' });
// => { meta: { 'og.title': 'Hello' } }
expandKeys({ 'tags.0': 'new', 'tags.label': 'x' }); // throws TypeError (tags is an array)
expandKeys({ plan: 'pro', 'plan.seats': 5 }); // throws TypeError (plan is a value)
expandKeys({ '__proto__.isAdmin': true, ok: 1 }); // => { ok: 1 }
expandKeys({}); // => {}