Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

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))
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #parent #child #json #tree #python
ADD COMMENT
Topic
Name
3+1 =