Flatten Nested Objects in JavaScript

Nested objects are a common data structure in JavaScript, providing a convenient way to organize and represent complex data. However, working with nested objects can sometimes be challenging, especially when you need to access specific properties or transform the data into a different format. In this post, we’ll explore how to flatten nested objects in JavaScript using a practical example.

Let’s consider the following nested object representing user data:

const user = {
  name: "Rowdy Coders",
  address: {
    primary: {
      house: "109",
      street: {
        main: 21,
        cross: ["32", "1"],
      },
    },
  },
};


Our goal is to flatten this nested object into a simpler, more manageable format as below.

{
  user_name: "Rowdy Coders",
  user_address_primary_house: "109",
  user_address_primary_street_main:21,
  user_address_primary_street_cross: ["32", "1"],
}


Specifically, we want to transform it into an object where each key is a flattened path to a property separated by ‘_’ and each value is the corresponding property value.

Remember that, this is one of the most asked interview questions pattern, and in an another interview, the interviewer asked similar question, but the interviewer expected the keys in camelCase as below.

{
  userName: "Rowdy Coders",
  userAddressPrimaryHouse: "109",
  userAddressPrimaryStreetMain: 21,
  userAddressPrimaryStreetCross: ["32", "1"],
}


Approach and Strategy:

To flatten the nested object, we’ll use a recursive function that traverses through the object’s properties. Here’s our approach:

  1. Start with an empty object to store the flattened result.
  2. Iterate through each key-value pair in the object.
  3. If the value is an object (but not an array), recursively flatten it.
  4. Concatenate the keys with underscores to create a flattened path.
  5. Add the flattened key-value pair to the result object.
  6. If the value is an array, handle each array item separately by appending its index to the flattened key.

Code Implementation:

function flattenObject(obj, prefix = '') {
  let flattened = {};

  for (let key in obj) {
    if (typeof obj[key] === 'object' && !Array.isArray(obj[key])) {
      flattened = {
        ...flattened,
        ...flattenObject(obj[key], `${prefix}${key}_`)
      };
    } else {
      flattened[`${prefix}${key}`] = obj[key];
    }
  }

  return flattened;
}

// Flatten the user object with "user_" prefix
const flattenedUser = flattenObject(user, 'user_');

console.log(flattenedUser);


Watch the video for better understanding:

Conclusion:

Flattening nested objects in JavaScript is a useful technique for simplifying complex data structures and making them easier to work with. By understanding the problem, defining a clear approach, and implementing a recursive solution, we can efficiently flatten nested objects and transform them into a more manageable format.