多维数组任意元素生成路径,并根据路径插入元素

一、多维数组生成路径

递归多维数组,给每一个元素生成一个路径

多维数组数据如下:

递归函数如下:

const addPath = (arr,path=[])=>{
    for(let i=0;i<arr.length;i++){
        let newpath = JSON.parse(JSON.stringify(path))
        newpath.push(i)
        if(arr[i].children){
            addPath(arr[i].children,newpath)
        }
        arr[i].path = newpath
    }
}
addPath(this.getTreeData)
console.log(123,this.getTreeData)        

如下path即为每一项元素的路径数组

二、给定位置,插入元素

//arr:目标数组,path:插入值所在路径,item:插入的值
function insertArray(arr, path, item) {
    let counter = 0;
    for (let v of path) {
        if (counter === path.length-1) {
            arr.splice(v, 0, item);
        } else {
            arr = arr[v];
        }
        counter++;
    }
}
let arr = [1, 2, 3, [4, 5, [6, 7, 8], 6, 7, 10]];
let path = [3, 2, 2];
insertArray(arr, path, 8);
console.log(arr); //[1, 2, 3, [4, 5, [6, 7, 8, 8], 6, 7, 10]]

 

posted @ 2022-04-11 18:34  盼星星盼太阳  阅读(62)  评论(0编辑  收藏  举报