2017-02-15 47 views
-1

請幫助我創建一個遞歸函數,將JSON從給定格式轉換爲下面的JSON。我有點失落如何去做。 謝謝你的幫助! 下面是我有和需要轉換的示例JSON格式。將JSON轉換爲另一種遞歸的JSON格式

這提供:

{ 
    "context": { 
    "device":   { 
     "localeCountryCode": "AX", 
     "datetime":   "3047-09-29T07:09:52.498Z" 
    }, 
    "currentLocation": { 
     "country": "KM", 
     "lon":  -78789486, 
    } 
    } 
} 

這是我想獲得:

{ 
    "label": "context", 
    "children": [ 
    { 
     "label": "device", 
     "children": [ 
     { 
      "label": "localeCountryCode" 
     }, 
     { 
      "label": "datetime" 
     } 
     ] 
    }, 
    { 
     "label": "currentLocation", 
     "children": [ 
     { 
      "label": "country" 
     }, 
     { 
      "label": "lon" 
     } 
     ] 
    } 
    ] 
} 
+3

什麼給定的格式?如果沒有你想要的格式和格式,我們不能回答這個問題。 – zack6849

+1

您似乎忘記了包含相關信息。請包括您正在使用的數據的示例。 – Lix

+0

謝謝你們,我添加了相關信息。 – Eden1971

回答

0

你可以檢查對象是truthy和獲取對象的鍵。然後返回每個鍵的對象與標籤和一個兒童屬性與函數的遞歸調用的結果。

function transform(o) { 
 
    if (o && typeof o === 'object') { 
 
     return Object.keys(o).map(function (k) { 
 
      var children = transform(o[k]); 
 
      return children ? { label: k, children: children } : { label: k }; 
 
     }); 
 
    } 
 
} 
 

 
var object = { context: { device: { localeCountryCode: "AX", datetime: "3047-09-29T07:09:52.498Z" }, currentLocation: { country: "KM", lon: -78789486, } } }, 
 
    result = transform(object); 
 

 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

+0

非常感謝! – Eden1971