Constructing a nested JSON object in JavaScript


We have a special kind of string that contains characters in couple, like this −

const str = "AABBCCDDEE";

We are required to construct an object based on this string which should look like this −

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

Notice that for each unique couple in the string we have a new sub object and the code property at any level represents a specific couple.

We can solve this problem using a recursive approach.

We will recursively iterate over the string to pick specific couple and assign a new sub object for it.

Therefore, let’s write the code for this function −

Example

The code for this will be −

const str = "AABBCCDDEE";
const constructObject = str => {
   const res = {};
   let ref = res;
   while(str){
      const words = str.substring(0, 2);
      str = str.substr(2, str.length);
      ref.code = words;
      ref.sub = {};
      ref = ref.sub;
   };
   return res;
};
console.log(JSON.stringify(constructObject(str), undefined, 4));

Output

The output in the console will be −

{
   "code": "AA",
   "sub": {
      "code": "BB",
      "sub": {
         "code": "CC",
         "sub": {
            "code": "DD",
            "sub": {
               "code": "EE",
               "sub": {}
            }
         }
      }
   }
}

Updated on: 20-Oct-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements