简体   繁体   中英

How to reformat a Nested JSON and restructure using javascript

My sample JSON , I would like to rebuild below json by removing "Child:" Object

{  
   "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.

You could use an iterative and recursive approach for moving DeviceList to the place of 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; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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