Constructing a nested JSON object in JavaScript

In JavaScript, we often need to construct nested objects from structured data. This article demonstrates how to build a nested JSON object from a string containing paired characters.

Problem Statement

Given a string with characters in pairs, we need to construct a nested object where each pair becomes a code property, and each level has a sub-object for the next pair.

Input string:

const str = "AABBCCDDEE";

Expected output structure:

const obj = {
    code: "AA",
    sub: {
        code: "BB",
        sub: {
            code: "CC",
            sub: {
                code: "DD",
                sub: {
                    code: "EE",
                    sub: {}
                }
            }
        }
    }
};

Solution Approach

We'll use an iterative approach to process the string in pairs of two characters. For each pair, we create a code property and prepare a sub object for the next iteration.

Implementation

const str = "AABBCCDDEE";

const constructObject = str => {
    const res = {};
    let ref = res;
    
    while(str) {
        const words = str.substring(0, 2);
        str = str.substring(2);
        ref.code = words;
        ref.sub = {};
        ref = ref.sub;
    }
    
    return res;
};

console.log(JSON.stringify(constructObject(str), null, 2));
{
  "code": "AA",
  "sub": {
    "code": "BB",
    "sub": {
      "code": "CC",
      "sub": {
        "code": "DD",
        "sub": {
          "code": "EE",
          "sub": {}
        }
      }
    }
  }
}

How It Works

The algorithm works by:

  1. Creating an initial empty object res and a reference pointer ref
  2. Iterating through the string, extracting 2 characters at a time
  3. Setting the code property to the current pair
  4. Creating an empty sub object for the next iteration
  5. Moving the reference pointer to the new sub object

Alternative Implementation

Here's a recursive version for comparison:

const constructObjectRecursive = (str, index = 0) => {
    if (index >= str.length) {
        return {};
    }
    
    return {
        code: str.substring(index, index + 2),
        sub: constructObjectRecursive(str, index + 2)
    };
};

const str2 = "XXYYZZ";
console.log(JSON.stringify(constructObjectRecursive(str2), null, 2));
{
  "code": "XX",
  "sub": {
    "code": "YY",
    "sub": {
      "code": "ZZ",
      "sub": {}
    }
  }
}

Conclusion

Both iterative and recursive approaches can construct nested JSON objects from paired character strings. The iterative method is more memory-efficient, while the recursive approach offers cleaner, more readable code for this pattern.

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

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements