Flatten JavaScript objects into a single-depth Object
Last Updated :
22 Dec, 2023
Given a nested JavaScript object, the task is to flatten the object and pull out all the values to a single depth. If the values are already at a single depth then it returns the result unaltered.
typeof() method:
The typeof() method is used in the script to check the type of JavaScript variable.
Syntax:
typeof(variable);
Parameters:
- Variable: The input variable.
Return Value: This method returns a string that contains the type of the passed variable.
Approach
- We make a function called flatten object which takes input of an object and returns an object.
- Loop through the object and check the type of the current property:
- If it is of type Object and it is not an Array, recursively call the function again.
- Otherwise, store the value in the result.
- Return the object.
Example: In this example, we are following the above approach.
Javascript
let ob = {
Company: "GeeksforGeeks" ,
Address: "Noida" ,
contact: +91-999999999,
mentor: {
HTML: "GFG" ,
CSS: "GFG" ,
JavaScript: "GFG"
}
};
const flattenObj = (ob) => {
let result = {};
for (const i in ob) {
if (( typeof ob[i]) === 'object' && !Array.isArray(ob[i])) {
const temp = flattenObj(ob[i]);
for (const j in temp) {
result[i + '.' + j] = temp[j];
}
}
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'
}
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...