Flatten Deep Object
JavaScript
medium
20 mins
Write a function flattenObject that takes a deeply nested JavaScript object and returns a new object where nested keys are represented in dot notation.
Input:
- A nested object with keys and values of any depth
Output:
- A new object where each key is a dot-separated path to the corresponding value
Example Inputs & Outputs
// Example 1: Input: { a: { b: 1 } } Output: { "a.b": 1 } // Example 2: Input: { a: { b: { c: 2 }, d: 3 } } Output: { "a.b.c": 2, "a.d": 3 } // Example 3: Input: { x: 1, y: { z: { k: 5 } } } Output: { "x": 1, "y.z.k": 5 } // Example 4: Input: {} Output: {} // Example 5: Input: { a: null, b: { c: undefined } } Output: { "a": null, "b.c": undefined }
Constraints & Edge Cases
- Keys are always strings
- Values may be any primitive or object
- Object may be empty
- Values like
null,undefined, or falsy primitives should be preserved - Does not mutate the original object
Companies:
airbnb
cisco
flipkart
Solve Similar questions 🔥
Want to upskill? Explore our courses!
Namaste DSA
Master DSA from scratch with numerous problems, and expert guidance.
Namaste React
Wanna dive deep into React and become Frontend Expert? Learn with me now!
Namaste Frontend System Design
The most comprehensive and detailed course for frontend system design.
Namaste Node.js
Wanna dive deep into Node.js? Enroll into `Namaste Node.js` now!
