Flatten a nested object
A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.
The task
Flatten nested plain objects into one level with dot-separated keys: `{ a: { b: 1 } }` becomes `{ "a.b": 1 }`. Only plain objects are opened up; arrays, dates, `null` and other values are kept as they are. An empty nested object adds no keys.
What this exercise teaches
Recursion carries the path so far as a prefix. The plain-object test is what keeps arrays, Dates and null intact; typeof alone says "object" for all of them.
A hint if you get stuck
Write a recursive helper that takes a prefix. For each entry, recurse when the value is a plain object (`Object.getPrototypeOf(v) === Object.prototype`), otherwise store it under `prefix.key`.
This exercise is part of Pro
Pro unlocks all 45 exercises, with worked solutions and progress saved to your account. The free exercises work without an account.
You create a free account first, so Pro is attached to it.
Monthly is charged today and then every month until you cancel, in one click from your account page. Lifetime is one payment with no renewals. Full refund within 14 days of paying.