Convert a string to hierarchical object - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Let’s say, 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

Example

Following is the code −

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

This will produce the following output in console −

{
   "code": "AA",
   "sub": {
       "code": "BB",
       "sub": {
           "code": "CC",
           "sub": {
               "code": "DD",
               "sub": {
                   "code": "EE",
                   "sub": {}
               }
           }
       }
   }
}
raja
Published on 18-Sep-2020 16:33:45
Advertisements