Back to Objects & JSONMedium
Exercise 7: Flatten Object (one level)
Problem Statement
Function `flattenObject(obj)` banao jo nested object ko one level flatten kare.
Example: flattenObject({a: 1, b: {c: 2}}) => {a: 1, "b.c": 2}
Sample Output:
flattenObject({a: 1, b: {c: 2}}) => {a: 1, "b.c": 2}
flattenObject({x: {y: {z: 1}}}) => {"x.y.z": 1}Solution
const flattenObject = (obj, prefix = "") => {
const result = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
const newKey = prefix ? `${prefix}.${key}` : key;
if (typeof obj[key] === "object" && obj[key] !== null && !Array.isArray(obj[key])) {
Object.assign(result, flattenObject(obj[key], newKey));
} else result[newKey] = obj[key];
}
}
return result;
};Explanation
Overall Goal:
- Nested object ko flatten karna.
Real world:
- Data transformation: nested to flat.
- Form data: nested form handling.