Recursively flat an object JavaScript

We are required to write a function that flattens nested objects by converting deeply nested properties into dot-notation keys. This is useful for data transformation and API processing.

If the input object is:

const input = {
   a: 0,
   b: {x: {y: 1, z: 2}},
   c: 3
};

Then the output of the function should be:

const output = {
   a: 0,
   'b.x.y': 1,
   'b.x.z': 2,
   c: 3
}

Recursive Flattening Function

We'll create a recursive function that traverses nested objects and builds flattened keys using dot notation:

const flattenObject = (obj, prefix = '', result = {}) => {
   const keys = Object.keys(obj);
   
   for (let i = 0; i 

{ a: 1, 'b.x.y': 1, 'b.x.z': 2, c: 3 }
{ a: 0, 'b.x.y': 1, 'b.x.z': 2, c: 3 }
{ a: 0, b: 0, c: 0 }

How It Works

The function uses three parameters:

  • obj: The object to flatten
  • prefix: Current key path (builds dot notation)
  • result: Accumulator object storing flattened keys

For each property, it checks if the value is a nested object. If so, it recursively calls itself with an updated prefix. Otherwise, it adds the key-value pair to the result.

Enhanced Version with Array Support

const flattenObjectAdvanced = (obj, prefix = '', result = {}) => {
   for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
         const newKey = prefix ? `${prefix}.${key}` : key;
         
         if (typeof obj[key] === 'object' && obj[key] !== null && !Array.isArray(obj[key])) {
            flattenObjectAdvanced(obj[key], newKey, result);
         } else {
            result[newKey] = obj[key];
         }
      }
   }
   return result;
};

const complexObj = {
   user: {
      name: 'John',
      address: {
         street: '123 Main St',
         city: 'Boston'
      }
   },
   items: [1, 2, 3]
};

console.log(flattenObjectAdvanced(complexObj));
{
  'user.name': 'John',
  'user.address.street': '123 Main St',
  'user.address.city': 'Boston',
  items: [ 1, 2, 3 ]
}

Conclusion

Recursive object flattening transforms nested objects into flat structures with dot-notation keys. This technique is valuable for data processing, form handling, and API transformations where nested data needs to be linearized.

Updated on: 2026-03-15T23:18:59+05:30

441 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements