Skip to content

Flatten & Expand

flatten() and expand() are inverses. They convert between a nested object and a single-level object whose keys are notations.

const obj = { car: { brand: 'Dodge', model: 'Charger', year: 1970 } };
Notation.create(obj).flatten().value;
// » {
// "car.brand": "Dodge",
// "car.model": "Charger",
// "car.year": 1970
// }

The opposite — nest dotted keys back under their parents. This is handy for flat rows coming out of a database or a form.

Take this flat row:

cases/api/flat-row.json
{
"id": 42,
"name": "Jane Doe",
"account.plan": "pro",
"account.billing.card.brand": "visa",
"account.billing.card.last4": "4242",
"profile.social.github": "jane"
}
import row from './flat-row.json' with { type: 'json' };
Notation.create(row).expand().value;
// » {
// id: 42,
// name: "Jane Doe",
// account: {
// plan: "pro",
// billing: { card: { brand: "visa", last4: "4242" } }
// },
// profile: { social: { github: "jane" } }
// }

flatten() then expand() returns the original shape — useful for diffing, patching, or storing nested data in a flat column:

const data = { user: { name: 'Jane', roles: ['editor'] } };
const flat = Notation.create(data).flatten().value;
// » { "user.name": "Jane", "user.roles[0]": "editor" }
Notation.create(flat).expand().value;
// » { user: { name: "Jane", roles: ["editor"] } }