Problem
Turning a nested object into flat key-value pairs in JavaScript is needed for form libraries, query strings, i18n message files, analytics payloads and diffing configs, and it is a common frontend interview exercise.
Write a function flatten(obj) that converts a nested object into a single-level object whose keys are dot-separated paths. For example, { a: { b: { c: 1 }, d: 2 } } becomes { "a.b.c": 1, "a.d": 2 }.
Requirements
- Each key in the result is the full path from the root to a value, with segments joined by
.. - Top-level keys that hold non-object values are kept as they are.
- Nested plain objects can be arbitrarily deep.
- Arrays are treated as values: they are copied into the result as-is, not expanded.
null,undefined, numbers, strings and booleans are leaf values and appear under their path.- The input object must not be mutated; return a new object.
Example
flatten({ a: { b: { c: 1 }, d: 2 } });
// { "a.b.c": 1, "a.d": 2 }
flatten({
user: { name: "Ana", address: { city: "Pune" } },
tags: ["x", "y"],
active: true,
meta: null,
});
// {
// "user.name": "Ana",
// "user.address.city": "Pune",
// "tags": ["x", "y"],
// "active": true,
// "meta": null
// }
Follow-ups
- How would you expand arrays using bracket notation such as
"a.b[0]"? - How would you write the reverse operation,
unflatten?