后台返回的树形数据没有统一字段的唯一id,树形数据,给每一层添加一个新的属性 key:‘xxx‘或id:‘xx‘

  • Post author:
  • Post category:其他


[{

"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": []
    }]
}]
}]

第一种方法:

function addKey(arr) {
    arr.forEach(function(el) {
        el.key = "new key"
            
        if (!el.subDepList || el.subDepList.length == 0) {
            return
        }

        addKey(el.subDepList)
    })
}

addKey(tree)

第二种方法:

function format(items) {
        return items.map(item => {
            const result = {...item, key: '1'}
            if (item.subDepList) {
                result.subDepList = format(item.subDepList)
            }
            return result
        })
    }

上面的key是固定的,如果想要添加唯一id的话,可以在外部定义一个为0的变量,赋值时自加一下key:value++,切记重新加载树形结构时,value要重置为0



版权声明:本文为weixin_44836531原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。