javascript - 从 JSON 中的分层 JSON 转换自顶点中的包装器 class 列表

javascript - hierarchical JSON from JSON converted from wrapper class list in apex

JSON 我通过序列化包装器得到 class 列表:

{
"tree": [{
    "Id": "1",
    "Children": ["2", "3"]
}, {
    "Id": "2",
    "Children": []
}, {
    "Id": "3",
    "Children": []
}, {
    "Id": "4",
    "Children": ["1"]
}, {
    "Id": "5",
    "Children": ["4", "6"]
}, {
    "Id": "6",
    "Children": []
}]

}

格式化JSON我需要分层形式:

{
"tree": [{
    "Id": "5",
    "Children": [{
        "Id": "4",
        "Children": [{
            "Id": "1",
            "Children": [{
                "Id": "2",
                "Children": []
            }, {
                "Id": "3",
                "Children": []
            }]
        }]
    }, {
        "Id": "6",
        "Children": []
    }]
}]

}

我需要获取 JSON 的层次结构形式,以便在 visualforce 页面上显示第 n 级的树结构。

这是这个问题的解决方案,它将JSON格式化为分层格式。

function convert(array)
{

var map = {}
for(var i = 0; i < array.length; i++)
{
    var obj = array[i]
    if(!(obj.Id in map))
    {
        map[obj.Id] = obj
        map[obj.Id].children = []
    }

    if(typeof map[obj.Id].parent == 'undefined')
    {
        map[obj.Id].Id = obj.Id
        map[obj.Id].parent= obj.parent
    }

    var parent = obj.parent || ' ';
    if(!(parent in map))
    {
        map[parent] = {}
        map[parent].children = []
    }

    map[parent].children.push(map[obj.Id])
}
return map[' ']
}