Flatten Nested Objects
JavaScript
medium
30 mins
Flattening makes it easier to work with deeply nested data.
- Accessing values becomes simpler ("user.address.city" instead of obj.user.address.city).
- Many databases, APIs, and config systems prefer flat key-value pairs.
- It helps in storing, searching, and comparing data more easily.
Input: A nested JavaScript object
Output: A flattened object with keys representing the full path using dot notation.
Constraints & Edge Cases
The object can be nested inside other objects at any number of levels
- Works for both shallow and deeply nested objects.
- Example:
{ a: { b: { c: { d: "x" } } } } → { "a.b.c.d": "x" }
Keys should be combined using . (dot notation)
- Nested keys are joined with a dot.
- Example:
{ address: { city: "Delhi" } } → { "address.city": "Delhi" }
Values can be strings, numbers, or other primitives
- Function must handle strings, numbers, booleans, etc.
- Example:
{ age: 30, active: true } → { "age": 30, "active": true }
Null values should be preserved
- If a value is null, keep it.
- Example:
{ profile: { bio: null } } → { "profile.bio": null }
Empty objects should not add any extra keys
- If a nested object is empty ({}), skip it.
- Examples:
{ user: {} } → {} { user: { name: "John", details: {} } } → { "user.name": "John" }
- Reason: Empty objects don’t contain useful data, so avoid creating meaningless keys.
Example 1:
Input:
let user = { name: 'John', address: { country: 'India', state: 'India', education: { school: "APS", year: 2021 } } };
Output:
{ 'user.name': 'John', 'user.address.country': 'India', 'user.address.state': 'India', 'user.address.education.school': 'APS', 'user.address.education.year': 2021 }
Example 2:
Input:
const data = { user: { name: "Bob", age: 25, contact: { email: null, phone: "999" } }, empty: {}, active: true };
Output:
{ "root.user.name": "Bob", "root.user.age": 25, "root.user.contact.email": null, "root.user.contact.phone": "999", "root.active": true }
Companies:
DP World
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!
