Q46 [Coding]: Write a function to flatten a deeply nested object using dot notation keys.
function flattenObject(obj, prefix = '') {
return Object.keys(obj).reduce((acc, key) => {
const pre = prefix.length ? prefix + '.' : '';
if (typeof obj[key] === 'object' && obj[key] !== null && !Array.isArray(obj[key])) {
Object.assign(acc, flattenObject(obj[key], pre + key));
} else {
acc[pre + key] = obj[key];
}
return acc;
}, {});
}
// Input: { a: { b: 2 } } -> Output: { 'a.b': 2 }
Key Takeaways
- Uses recursion to append nested keys into dot-separated paths.
- Ignores primitive key value properties while drilling into child object trees.
Knowledge Check
What is the flattened key output for { user: { address: { city: 'Paris' } } }?