DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 967,611 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Vishal Gupta
Vishal Gupta

Posted on • Updated 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.

Google Cloud Superstar

Use your favorite Google Cloud APIs with MongoDB Atlas to build a highly-scalable modern application for your entry in the DEV x MongoDB Atlas Hackathon 2022.

β†’ Get Started