function listToTree(data) {
    let arr = JSON.parse(JSON.stringify(data));
    const listChildren = (obj, filter) = > {
        [arr, obj.children] = arr.reduce((res, val) = > {if (filter(val)) res[1].push(val); else res[0].push(val);returnres; }, [[], []]); obj.children.forEach(val= > {
            if (arr.length) listChildren(val, obj= > obj.pId === val.id);
        });
    };
    const tree = {};
    listChildren(tree, val= > arr.findIndex(i= > i.id === val.pId) === -1);// Find the parent element
    return tree.children;
}

let array = [
    {
        id:1.name:"ceshi".pId:9999
    },
    {
        id:2.name:"ceshi2".pId: 9999
    },
    {
        id:3.name:"sahd".pId:1
    },
    {
        id:4.name:"ooopkhh".pId:2,}]console.log(listToTree(array))

Copy the code