Thursday, October 23, 2025
HomeLanguagesJavascriptFlatten JavaScript objects into a single-depth Object

Flatten JavaScript objects into a single-depth Object

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 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: This method accept one parameter as mentioned above and described below:

  • Variable: The input variable.

Return Value: This method returns a string which contains the type of the passed variable.

Approach:

  1. We make a function called flatten object which takes input of an object and returns an object.
  2. 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.
  3. Return the object.

Example:

Javascript




// Declare an object
let ob = {
    Company: "neveropen",
    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: 'neveropen',
  Address: 'Noida',
  contact: -999999908,
  'mentor.HTML': 'GFG',
  'mentor.CSS': 'GFG',
  'mentor.JavaScript': 'GFG'
}
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS