DEV Community

Vishal Gupta
Vishal Gupta

Posted on • Edited on

Flattening a Javascript Object

Flattening a javascript object is a very common question asked in UI Interviews.

Flattening deeply nested object can be easily achieved by using recursive technique.

The code depends on how a flattened object should look like...

// input
var user = {
  name: "Vishal",
  address: {
    primary: {
      house: "109",
      street: {             
        main: "21",
        cross: "32"
      }
    }
  }
};

//output
{
  user_name: "Vishal",
  user_address_primary_house: "109",
  user_address_primary_street_main: "21",
  user_address_primary_street_cross: "32",
}

Algo:

  1. Iterate over keys of the object
  2. Append child key name into the parent key name
  3. If the child key's value is an object again call the same function
  4. Else assign key to the new value

Code:

var flattendObj = {};
const flattenObject = (obj, keyName) => {
  Object.keys(obj).forEach(key => {
    var newKey = `${keyName}_${key}` 
    if (typeof obj[key] === "object") {
      // calling the function again
      flattenObject(obj[key], newKey);
    } else {
      flattendObj[newKey] = obj[key];
    }
  });
};
console.log(flattendObj);

Recursion is magical, if you know where to stop. 🌀

Follow me for more such content.

Aiming to post the solution of such problems daily. 🔥

Challenge me with more problems. 💪

Top comments (1)

Collapse
 
vishalvishalgupta profile image
vishalvishalgupta

This will not pass in many test cases. Its not a right code.