2017-02-11 68 views
1

我的樣品JSON,我想通過刪除重建以下JSON「孩子:」對象如何使用JavaScript來重新嵌套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內容看起來像提供的示例。

+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; }

要 '跳過'`Child`關鍵
+0

您需要處理「孩子」爲空的情況。它仍然應該替換爲「DeviceList」= null。 –

+1

@JeffM,請看編輯。 –