Tree data, adding a new attribute key:'xxx' to each layer

[{

]
"id": 1,
"name": "",
"depCode": "MI00",
"fatherId": null,
"fatherName": null,
"subDepList": [{
    "id": 2,
    "name": "",
    "depCode": "MI0001",
    "fatherId": 1,
    "fatherName": "",
    "subDepList": [{
        "id": 3,
        "name": "1",
        "depCode": "MI000101",
        "fatherId": 2,
        "fatherName": "",
        "subDepList": [{
            "id": 10,
            "name": "test",
            "depCode": "MI00010103",
            "fatherId": 3,
            "fatherName": "1",
            "subDepList": []
        }, {
            "id": 6,
            "name": "1",
            "depCode": "MI00010101",
            "fatherId": 3,
            "fatherName": "1",
            "subDepList": []
        }, {
            "id": 7,
            "name": "2",
            "depCode": "MI00010102",
            "fatherId": 3,
            "fatherName": "1",
            "subDepList": []
        }]
    }, {
        "id": 4,
        "name": "2",
        "depCode": "MI000102",
        "fatherId": 2,
        "fatherName": "",
        "subDepList": []
    }, {
        "id": 5,
        "name": "3",
        "depCode": "MI000103",
        "fatherId": 2,
        "fatherName": "",
        "subDepList": []
    }]
}]

}]

solve

Mar.30,2021

const addKey = arr => arr.map(item => ({
  ...item,
  key: 'xxx',
  subDepList: addKey(item.subDepList)
}))

const result = addKey(arr)

clipboard.png



    function format(items) {
        return items.map(item => {
            const result = {...item, key: '1'}
            if (item.subDepList) {
                result.subDepList = format(item.subDepList)
            }
            return result
        })
    }
if you solve the problem, help adopt it. Of course, it's better to click like ~
Menu