Flatten nested Object
Objective: Write a function that takes a deeply nested object and returns a flat object with all keys flattened.
Instructions:
- Create a function called
flattenObject
that accepts an object with nested objects at various levels.
- The function should return a new object where all nested keys are flattened into a single-level object, with the keys representing the nested structure using dot notation (e.g.,
'key1.key2': value
).
Example:
flattenObject({
a: 1,
b: {
c: 2,
d: {
e: 3
}
}
});
// Output: { 'a': 1, 'b.c': 2, 'b.d.e': 3 }
Requirements:
- The function must handle objects with multiple levels of nesting.
- The function should work recursively to flatten deeply nested objects.
- You cannot use any built-in flattening utilities.
Hints:
- Use
recursion
to flatten nested objects.
- Use dot notation to
concatenate
keys as you go deeper into nested objects.
Bonus:
- Add a second argument to the function that limits how deep the object should be flattened.