标记对象父级索引

let dataList = [
    {
        id: 148
        pid: 0
        name: "将军"
        checked: true,
        child: [
            {
                id: 154
                pid: 148
                name: "师长"
                checked: true
                child: [
                    {id: 182, pid: 154,name: "营长1", checked: true, level: 2, has: false},
                    {id: 210, pid: 154,name: "营长2", checked: true, level: 2, has: false}
                ]
                level: 1
                has: false
            }
        ]
        level: 0
        has: false
    }
]

上面这个数据对象如何变成下面这种,记住每一个index自己索引的同时,还要记住他的上一级索引

let dataList = [
    {
        id: 148
        pid: 0
        name: "将军"
        checked: true,
        index: [0]
        child: [
            {
                id: 154
                pid: 148
                name: "师长"
                checked: true
                child: [
                    {id: 182, pid: 154,name: "营长1", checked: true, level: 2, has: false,index: [0,0,0]},
                    {id: 210, pid: 154,name: "营长2", checked: true, level: 2, has: false,index: [0,0,1]}
                ]
                level: 1
                has: false,
                index: [0,0]
            }
        ]
        level: 0
        has: false
    }
]
阅读 1.6k
1 个回答

递归

function loop(data, level){
    level = level || []
    data.forEach((item,index) => {
        item.index = level.concat(index)
        if(Array.isArray(item.child)){
            loop(item.child, item.index)
        }
    })
}

loop(dataList);
console.log(dataList)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题