Нужен объект Json, который поддерживает таблицу простого дерева NG с заданным массивом объектов

#angular #recursion #primeng #treetable #primeng-treetable

Вопрос:

У меня есть массив объектов, в котором есть данные о родителях и потомках, и я хочу преобразовать их в формат данных, поддерживаемый таблицей дерева Ng.

У меня есть массив JSOn, как показано ниже :

 [
    {
        "bizUnitID": 1,
        "bizUnitName": "SYSTEM",
        "description": "",
        "bizUnitParent": 0
    },
    {
        "bizUnitID": 6,
        "bizUnitName ": "Child BU",
        "description": " Child  BU",
        "bizUnitParent": 1
    },
    {
        "bizUnitID": 15,
        "bizUnitName": "Child1_BU",
        "description": " Child1_BU",
        "bizUnitParent": 6
    },
    {
        "bizUnitID": 16,
        "bizUnitName": " Child2_BU ",
        "description": " Child2_BU ",
        "bizUnitParent": 6
    }
]
 

То, что от меня ожидают, выглядит следующим образом :

 [
    {
        "data": [
            {
                "data": {
                    "BizUnitId": "1",
                    "BizUnitName": "System",
                    "Description": "System"
               "bizUnitParent": 0
                },
                "children": [
                    {
                        "data": {
                            "bizUnitID": 6,
                            "bizUnitName ": "Child BU",
                            "description": " Child  BU",
                            "bizUnitParent": 1
                        },
                        "children": [
                            {
                                "data": {
                                    "bizUnitID": 16,
                                    "bizUnitName": " Child1_BU ",
                                    "description": " Child1_BU ",
                                    "bizUnitParent": 6
                                }
                            },
                            {
                                "data": {
                                    "bizUnitID": 15,
                                    "bizUnitName": "Child2_BU",
                                    "description": " Child2_BU",
                                    "bizUnitParent": 6
                                }
                            }
                        ]
                    }
                ]
            }
        ]
    }
]
 

Чтобы получить эту структуру, я попробовал приведенное ниже решение, которое было предложено кем-то в одном из вопросов. Приведенный ниже код привязывает данные к родительской и дочерней таблицам дерева, но не к дочернему элементу Childs.

Любые изменения, необходимые для приведенного ниже кода. пожалуйста, предложите.

 // find leaf who does not have child using recursive


function findLeaf(data, curIndex, parIndex) {
    const childId = data[curIndex].dataId;
    for(let i = 0; i < data.length; i  ) {
        if(data[i].parentId == childId) {
            return findLeaf(data, i, curIndex);
        }
    }
    return [curIndex, parIndex];
}

// check if array contains child 
// and returns child index and parent index
function getChildIndex(data) {
    for(let i = 0; i < data.length; i  ) {
        if(data[i].parentId != null) {
            for(let j = 0; j < data.length; j  ) {
                if(data[j].dataId == data[i].parentId) 
                    return [i, j];
            }
        }
    }
    return [-1];
}

function normalize(data) {
    // get child and start from it
    let childIndex = getChildIndex(data);
    while(childIndex[0] !== -1) {
        // check if dataId and parentId are same
        // if it's same, set parentId to null
        // to remove infinite recursive call
        if(childIndex[0] == childIndex[1]) {
            data[childIndex[0]].parentId = null;
            childIndex = getChildIndex(data);
            continue;
        }
        // get leaf index and its parent index
        const [cIndex, pIndex] = findLeaf(data, childIndex[0], childIndex[1]);
        // correcting data structure before inserting child to parent
        if(data[pIndex].children == undefined)
            data[pIndex].children = [];
        delete data[cIndex].parentId;
        delete data[cIndex].dataId;
        if(data[cIndex].children != undefined) {
            cchildren = data[cIndex].children;
            delete data[cIndex].children;
            data[cIndex] = { data: data[cIndex], children: cchildren };
        }
        // insert children to parent
        data[pIndex].children.push({ data: data[cIndex] });
        // reconfiguring data by removing inserted child
        data = [...data.slice(0, cIndex), ...data.slice(cIndex 1)];
        // check if there is child left, to loop again
        childIndex = getChildIndex(data);
    }
    // there is no child, it's time to normalize parent structure.
    for(let i = 0; i < data.length; i  ) {
        delete data[i].dataId;
        delete data[i].parentId;
        //const children = data[i].children;
        //delete data[i].children;
        //data[i] = children ? { data: data[i], children: children } : { data: data[i] }
    }

    return data;
}

console.log(normalize(data));
 

Комментарии:

1. Может ли кто-нибудь, пожалуйста, помочь мне приступить к работе над этим.