使用递归JavaScript将JSON转换为另一种JSON格式

假设我们有以下JSON对象-

const obj = {

   "context": {

      "device": {

         "localeCountryCode": "AX",

         "datetime": "3047-09-29T07:09:52.498Z"

      },

      "currentLocation": {

         "country": "KM",

         "lon": -78789486,

      }

   }

};

我们需要编写一个JavaScript递归函数,该函数最初采用一个这样的数组。该函数应将上述对象拆分为“标签”-“子级”格式。

因此,上述对象的输出应类似于-

const output = {

   "label": "context",

   "children": [

      {

         "label": "device",

         "children": [

         {

            "label": "localeCountryCode"

         },

         {

            "label": "datetime"

         }

      ]

   },

   {

      "label": "currentLocation",

      "children": [

            {

               "label": "country"

            },

            {

               "label": "lon"

            }

         ]

      }

   ]

}

为此的代码将是-

示例

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));

输出结果

控制台中的输出将是-

[

   {

      "label": "context",

      "children": [

         {

            "label": "device",

            "children": [

               {

                  "label": "localeCountryCode"

               },

               {

               "label": "datetime"

               }

            ]

         },

         {

            "label": "currentLocation",

            "children": [

                  {

                     "label": "country"

                  },

                  {

                     "label": "lon"

                  }

               ]

            }

      ]

   }

]

以上是 使用递归JavaScript将JSON转换为另一种JSON格式 的全部内容, 来源链接: utcz.com/z/330847.html

回到顶部