📜  父子到 json 树 python - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:03:37.854000             🧑  作者: Mango

代码示例1
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))