如何将平面JavaScript对象数组转换为嵌套的分层JSON结构?

时间:2014-09-12 13:32:10

标签: javascript

我需要转换以下平面JavaScript对象数组:

[ [ { "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 个答案:

答案 0 :(得分: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;
}