Saran Dev Saran Dev - 3 months ago 26
JSON Question

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

JSON I got by serializing wrapper class list:

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


}

Formatted JSON I need in hierarchical form:

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


}

I need to get this hierarchical form of JSON to show the tree structure on visualforce page upto nth level.

Answer

This is the solution for this problem, it will format this JSON in hierarchical format.

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[' ']
}