Implement a function to flatten a deeply nested object, converting nested keys to a single key path (e.g., { a: { b: 1 } } to { "a.b": 1 }).
HardProblem Statement
Implement a function to flatten a deeply nested object, converting nested keys to a single key path (e.g., { a: { b: 1 } } to { "a.b": 1 }).
Sample Input
{ a: { b: 1, c: { d: 2 } } }Sample Output
{ 'a.b': 1, 'a.c.d': 2 }
Limits
Time: 2s · Memory: 256 MB
Code Editor
00:00
// Flatten a deeply nested object
function flattenObject(obj, prefix = '', result = {}) {
// Iterate through object keys
// Concatenate nested keys to form path
// Recursively flatten nested objects
}
const nestedObj = { a: { b: 1, c: { d: 2 } } };
console.log(flattenObject(nestedObj));
Input
{ a: { b: 1, c: { d: 2 } } }Expected Output
{ 'a.b': 1, 'a.c.d': 2 }