2014-09-12 168 views
-3

我需要改變以下平板JavaScript對象數組:如何將平面JavaScript對象數組轉換爲嵌套層次JSON結構?

[ [ { "name": "child1" }, { "name": "parent1" }, { "name": "grandparent1" } ], [ { "name": "child2" }, { "name": "parent2" }, { "name": "grandparent2" } ] ] 

分爲以下幾個層次的嵌套JSON結構:

{ 
    "data": [ 
     { 
      "name": "child1", 
      "parent": { 
       "name": "parent1", 
       "parent": { 
        "name": "grandparent1", 
        "parent": null 
       } 
      } 
     }, 
     { 
      "name": "child2", 
      "parent": { 
       "name": "parent2", 
       "parent": { 
        "name": "grandparent2", 
        "parent": null 
       } 
      } 
     } 
    ] 
} 

我怎麼能在JavaScript做到這一點?

+1

通過編寫代碼並向我們展示您首先嚐試過的內容。你可以用簡單的循環和/或像'reduce'(或其他)這樣的數組原型方法輕鬆地完成它。 – Ian 2014-09-12 13:33:00

+0

如果數組的模式總是相同的,那麼它不是很複雜 – T00rk 2014-09-12 13:35:00

+1

究竟是什麼'{child1,parent1,grandparent1} '?請以正確的JSON形式發佈輸入,就像您對預期輸出所做的一樣。 – Bergi 2014-09-12 13:35:28

回答

1

好吧,

我想出了下面的解決方案,似乎工作正常。

var familiesArr = [ [ { "name": "child1" }, { "name": "parent1" }, { "name": "grandparent1" } ], [ { "name": "child2" }, { "name": "parent2" }, { "name": "grandparent2" } ] ]; 
var hierarchicalFamilies = createHierarchicalFamilies(familiesArr); 

function createHierarchicalFamilies(familiesArr) { 
    var familyHierarchy = new Array();   
    for (var i=0; i<familiesArr.length; i++) { 
     var family = familiesArr[i]; 
     familyHierarchy.push(addFamilyMember(family.slice())); 
    } 
    return familyHierarchy; 
} 

function addFamilyMember(family) { 
    if (family.length <= 0) { 
     return null; 
    } 
    var familyMemberNode = family[0]; 
    var familyMember = new Object(); 
    familyMember.name = familyMemberNode.name; 
    familyMember.parent = addFamilyMember(family.slice(1)); 
    return familyMember; 
}   
相關問題