How to convert square bracket object keys into nested object in JavaScript?

In JavaScript, objects with square bracket notation in their keys can be converted into properly nested objects. This is useful when dealing with flat data structures that represent nested relationships.

Consider an object with square bracket notation:

const flatObj = { "object[foo][bar][ya]": 100 };
console.log("Original object:", flatObj);
Original object: { 'object[foo][bar][ya]': 100 }

We want to convert this into a nested structure where each bracket represents a deeper level of nesting.

Understanding the Problem

The goal is to transform a key like "object[foo][bar][ya]" into a nested object structure:

{
  "object": {
    "foo": {
      "bar": {
        "ya": 100
      }
    }
  }
}

Solution: Converting Square Brackets to Nested Objects

const obj = { "object[foo][bar][ya]": 100 };

const constructNestedObject = (flatObj) => {
    // Get the first (and likely only) key from the object
    const key = Object.keys(flatObj)[0];
    const value = flatObj[key];
    
    // Split by '[' and clean up the brackets
    const keys = key.split('[').map(el => el.replace(']', ''));
    
    let result = {};
    
    // Build the nested structure from inside out
    keys.reverse().forEach((currentKey, index) => {
        if (index === 0) {
            // First iteration: set the innermost value
            result[currentKey] = value;
        } else {
            // Subsequent iterations: wrap the current result
            const temp = {};
            temp[currentKey] = result;
            result = temp;
        }
    });
    
    return result;
};

const nestedObj = constructNestedObject(obj);
console.log(JSON.stringify(nestedObj, null, 2));
{
  "object": {
    "foo": {
      "bar": {
        "ya": 100
      }
    }
  }
}

How It Works

The algorithm works in these steps:

  1. Extract the key: Get the square bracket notation key from the object
  2. Parse the path: Split by '[' and remove ']' characters to get individual keys
  3. Reverse and build: Start from the innermost level and work outward, creating nested objects
  4. Assign value: The original value is placed at the deepest nesting level

Handling Multiple Properties

For objects with multiple square bracket properties:

const multiObj = {
    "user[profile][name]": "John",
    "user[profile][age]": 30,
    "settings[theme]": "dark"
};

const convertMultipleKeys = (flatObj) => {
    let result = {};
    
    Object.keys(flatObj).forEach(key => {
        const value = flatObj[key];
        const keys = key.split('[').map(el => el.replace(']', ''));
        
        let current = result;
        for (let i = 0; i < keys.length - 1; i++) {
            if (!current[keys[i]]) {
                current[keys[i]] = {};
            }
            current = current[keys[i]];
        }
        current[keys[keys.length - 1]] = value;
    });
    
    return result;
};

console.log(JSON.stringify(convertMultipleKeys(multiObj), null, 2));
{
  "user": {
    "profile": {
      "name": "John",
      "age": 30
    }
  },
  "settings": {
    "theme": "dark"
  }
}

Conclusion

Converting square bracket notation to nested objects involves parsing the key structure and building objects from the inside out. This technique is particularly useful when working with form data or APIs that use bracket notation to represent nested data structures.

Updated on: 2026-03-15T23:19:00+05:30

836 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements