怎么动态添加对象属性

let dataList = [
    {
        name: "将军",
        checked: true,
        index:[0],
        child: [
            {
                name: "师长",
                checked: true,
                index:[0,0],
                child: [
                    {name: "营长1", checked: true, level: 2,index:[0,0,0]},
                    {name: "营长2", checked: true, level: 2,index:[0,0,1]}
                ],
                level: 1
            }
        ],
        level: 0
    }
]

上面每个index都标记着当着所有索引的位置
假如我点击获取到页面的index是[0,0,0]
我想改变他的所有的父级checked为false
考虑到层级可能会很多层不可能写死
想根据索引去动态操作他的父级,结果如下,这个要怎么处理

this.dataList[0].checked = false;
this.dataList[0].child[0].checked = false;
阅读 1.9k
2 个回答
//假设当前node是
let node = dataList[0].child[0].child[0]

//那么
//从该元素开始
pindex = node.index
//从该元素开始
//let pindex = node.index.slice(0, -1)

pindex.reduce((data, item) => {
    let parent = data[item]
    parent.checked = false

    return parent.child
}, dataList)

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