A nested JavaScript object can be flattened into a single-level object by recursively traversing its properties and combining nested keys using a separator such as ..
- Use typeof to identify nested objects.
- Recursively process nested objects while preserving their key paths.
- Keep primitive values and arrays as they are.
Approach: Using Recursion and typeof
The recursive approach checks each property and calls the function again when a nested object is found. The nested keys are combined using . to create a single-level object.
// Declare an object
let ob = {
Company: "GeeksforGeeks",
Address: "Noida",
contact: +91-999999999,
mentor: {
HTML: "GFG",
CSS: "GFG",
JavaScript: "GFG"
}
};
// Declare a flatten function that takes
// object as parameter and returns the
// flatten object
const flattenObj = (ob) => {
// The object which contains the
// final result
let result = {};
// loop through the object "ob"
for (const i in ob) {
// We check the type of the i using
// typeof() function and recursively
// call the function again
if ((typeof ob[i]) === 'object' && !Array.isArray(ob[i])) {
const temp = flattenObj(ob[i]);
for (const j in temp) {
// Store temp in result
result[i + '.' + j] = temp[j];
}
}
// Else store ob[i] in result directly
else {
result[i] = ob[i];
}
}
return result;
};
console.log(flattenObj(ob));
Output
{
Company: 'GeeksforGeeks',
Address: 'Noida',
contact: -999999908,
'mentor.HTML': 'GFG',
'mentor.CSS': 'GFG',
'mentor.JavaScript': 'GFG'
}