如何使用javascript重新格式化嵌套的JSON和重组

时间:2017-02-11 18:07:21

标签: javascript json

我的示例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"
         }
      ]
   }
}

新结构应如下所示

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

我正在寻找一个动态json树结构的嵌套递归解决方案,其中我的JSON内容看起来就像提供的样本一样。

1 个答案:

答案 0 :(得分:1)

您可以使用迭代和递归方法将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; }