Middle
Practical task: implement an equivalent of the Array.flat() method, but for objects (recursive flattening of nested objects).
sobes.tech AI
Answer from AI
To implement an equivalent of Array.flat() for objects, you need to recursively traverse all nested objects and "pull out" their properties into a single flat object with keys reflecting the path to the value.
Example in JavaScript:
function flattenObject(obj, prefix = '') {
let result = {};
for (const [key, value] of Object.entries(obj)) {
const newKey = prefix ? `${prefix}.${key}` : key;
if (value && typeof value === 'object' && !Array.isArray(value)) {
Object.assign(result, flattenObject(value, newKey));
} else {
result[newKey] = value;
}
}
return result;
}
// Usage example:
const nested = {
a: 1,
b: {
c: 2,
d: {
e: 3
}
}
};
console.log(flattenObject(nested));
// Output:
// { 'a': 1, 'b.c': 2, 'b.d.e': 3 }
This approach allows obtaining a flat object with keys that reflect the nested structure through dots.