Convert JSON to another JSON format with recursion JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented ProgrammingJSON

Suppose, we have the following JSON object −

const obj = {
   "context": {
      "device": {
         "localeCountryCode": "AX",
         "datetime": "3047-09-29T07:09:52.498Z"
      },
      "currentLocation": {
         "country": "KM",
         "lon": -78789486,
      }
   }
};

We are required to write a JavaScript recursive function that initially takes in one such array.The function should split the above object into a "label" - "children" format.

Therefore, the output for the above object should look like −

const output = {
   "label": "context",
   "children": [
      {
         "label": "device",
         "children": [
         {
            "label": "localeCountryCode"
         },
         {
            "label": "datetime"
         }
      ]
   },
   {
      "label": "currentLocation",
      "children": [
            {
               "label": "country"
            },
            {
               "label": "lon"
            }
         ]
      }
   ]
}

The code for this will be −

Example

const obj = {
   "context": {
      "device": {
         "localeCountryCode": "AX",
         "datetime": "3047-09-29T07:09:52.498Z"
      },
      "currentLocation": {
         "country": "KM",
         "lon": -78789486,
      }
   }
};
const transformObject = (obj = {}) => {
   if (obj && typeof obj === 'object') {
      return Object.keys(obj).map((el) => {
         let children = transformObject(obj[el]); return children ? {
             label: el, children: children } : {
            label: el
         };
      });
   };
};
console.log(JSON.stringify(transformObject(obj), undefined, 4));

Output

And the output in the console will be −

[
   {
      "label": "context",
      "children": [
         {
            "label": "device",
            "children": [
               {
                  "label": "localeCountryCode"
               },
               {
               "label": "datetime"
               }
            ]
         },
         {
            "label": "currentLocation",
            "children": [
                  {
                     "label": "country"
                  },
                  {
                     "label": "lon"
                  }
               ]
            }
      ]
   }
]
raja
Published on 21-Nov-2020 05:41:47
Advertisements