image.png

    1. const arr = [{ "id": 1 },
    2. { "id": 2, "fatherId": 1 },
    3. { "id": 3, "fatherId": 2 },
    4. { "id": 4, "fatherId": 1 }]
    5. function makeTree(arr) {
    6. for (let item of arr) {
    7. if (item.fatherId) {
    8. let father = arr.find(fa => fa.id === item.fatherId)
    9. if (father.children) {
    10. father.children.push(item)
    11. } else { father.children = [item] }
    12. }
    13. }
    14. return arr.filter(item => !item.fatherId)
    15. }
    16. let arrNew = makeTree(arr)
    17. console.log(arrNew);