parent child to json tree python 1

parent child to json tree python

var arry = [{
    "parentId": null,
    "moduleId": 1

 },
 {
    "parentId": 1,
    "moduleId": 2

 },
 {
    "parentId": 1,

    "moduleId": 3

 },
 {
    "parentId": null,
    "moduleId": 4

 },
 {
    "parentId": null,
    "moduleId": 5   
 },
 {

    "parentId": 3, 
    "moduleId": 6 
 }
];

function convert(array){
    var map = {};
    for(var i = 0; i < array.length; i++){
        var obj = array[i];
        obj.children= [];

        map[obj.moduleId] = obj;

        var parent = obj.parentId || '-';
        if(!map[parent]){
            map[parent] = {
                children: []
            };
        }
        map[parent].children.push(obj);
    }
    return map['-'].children;
}

var r = convert(arry)
console.log('array', r);
console.log('result', JSON.stringify(r))

Here is what the above code is Doing:
1. It creates a map of the array elements.
2. It then iterates through the array and adds a children property to each element.
3. It then checks if the parentId is null or not. If it is null, it assigns the parentId to '-'.
4. It then checks if the parentId exists in the map. If it doesn't, it creates a new object with a children property.
5. It then pushes the object to the children array of the parent.
6. Finally, it returns the children array of the root element.

Similar Posts