Write a function `flattenObject(obj)` that flattens a nested object into dot-notation keys. `{a: {b: 1}}` becomes `{"a.b": 1}`.
Problem Statement
Write a function `flattenObject(obj)` that flattens a nested object into dot-notation keys. `{a: {b: 1}}` becomes `{"a.b": 1}`.
Complexity
Time Complexity: -
Space Complexity: -
Hints
š” Hint 1:
Recursion is key ā check if a value is a plain object.
š” Hint 2:
Build the key path as you recurse deeper (e.g., "a.b.c").
š” Hint 3:
If value is an object (not null, not array), recurse. Otherwise, assign to result with the full key path.
ā
Solution:
```javascript
function flattenObject(obj, prefix = "", result = {}) {
for (const key in obj) {
const fullKey = prefix ? `${prefix}.${key}` : key;
if (typeof obj[key] === "object" && obj[key] !== null && !Array.isArray(obj[key])) {
flattenObject(obj[key], fullKey, result);
} else {
result[fullKey] = obj[key];
}
}
return result;
}
```