简体   繁体   English

如何重新格式化嵌套的 JSON 并使用 javascript 进行重组

[英]How to reformat a Nested JSON and restructure using javascript

My sample JSON , I would like to rebuild below json by removing "Child:" Object我的示例 JSON ,我想通过删除“Child:”对象在 json 下重建

{  
   "Child":{  
      "DeviceList":[  
         {  
            "Child":null,
            "DeviceId":"7405618",
            "Signal":"-90"
         },
         {  
            "Child":{  
               "DeviceList":[  
                  {  
                     "Child":{  
                        "DeviceList":[  
                           {  
                              "Child":null,
                              "DeviceId":"3276847",
                              "Signal":"-86"
                           }
                        ]
                     },
                     "DeviceId":"2293808",
                     "Signal":""
                  }
               ]
            },
            "DeviceId":"4915247",
            "Signal":"-90"
         }
      ]
   }
}

New structure should look like this新结构应该是这样的

{  
   "DeviceList":[  
      {  
         "DeviceList":null,
         "DeviceId":"7405618",
         "Signal":"-90"
      },
      {  
         "DeviceList":[  
            {  
               "DeviceList":[  
                  {  
                     "DeviceList":null,
                     "DeviceId":"3276847",
                     "Signal":"-86"
                  }
               ],
               "DeviceId":"2293808",
               "Signal":""
            }
         ],
         "DeviceId":"4915247",
         "Signal":"-90"
      }
   ],
   "DeviceId":"4915247",
   "Signal":"-90"
}

I am looking for a nested recursive solution for a dynamic json tree structure where my JSON content will look like the sample provided.我正在为动态 json 树结构寻找嵌套递归解决方案,其中我的 JSON 内容将类似于提供的示例。

You could use an iterative and recursive approach for moving DeviceList to the place of Child .您可以使用迭代和递归方法将DeviceList移动到Child的位置。

 var data = { Child: { DeviceList: [{ Child: null, DeviceId: "7405618", Signal: "-90" }, { Child: { DeviceList: [{ Child: { DeviceList: [{ Child: null, DeviceId: "3276847", Signal: "-86" }] }, DeviceId: "2293808", Signal: "" }] }, DeviceId: "4915247", Signal: "-90" }] } }; [data].forEach(function iter(a) { if ('Child' in a) { a.DeviceList = a.Child && a.Child.DeviceList; delete a.Child; if (Array.isArray(a.DeviceList)) { a.DeviceList.forEach(iter); } } }); console.log(data);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM