1
  
  向父节点动态插入子节点,如何更新父数组。
  
  例如 已知索引为
  const pathKey = [0, 0, 1]
  
  已知父节点为
  const apple = [
    {name: 1, 
      children:[
      {name: 32,
        children:[{
          name: 1
        }, {
          name: 2
        }]
      }]
    },
    {name: 13}
  ]
  
  待插入子节点为:
  const arr = [{ name: 999 }]
  
  需要实现 apple[0].children[0].children[1].children = arr
  
  pathKey是长度不定的。求帮助~
2018-12-18 提问
4 个回答
0

你写个递归函数吧!,判断只要有children,就继续执行自身,直到没有children,就直接插入数据。
function diedai(arr){

for(let value of arr){
      if(value.children&&value.children.length>0){
          diedai(value.children)
      } else{
          value.children=arr
      }
}

}

0
  function insert(node, paths, val) {
    if (!node) {
      return;
    }
    let key = paths.shift();
    if (Array.isArray(node)) {
      //实际上根结点是多个
      node = node[key];
      return insert(node, paths, val);
    }
    if (paths.length === 0) {
      return (node.children = val);
    }

    node.children = node.children || [];

    node = node.children[key] ? node.children[key] : (node.children[key] = { name: "default", children: [] });

    insert(node, paths, val);
  }
  insert(apple, paths, arr);
0

我的方法只能在新的数组中添加你想要的效果...仅供参考

(function setArr(){
    //定义初始值
    const pathKey = [0, 0, 1]  
    const apple = [
    {name: 1, 
    children:[{name: 32,children:[{name: 1},{name: 2}]}]
    },
    {name: 13}]
    var arr = [{ name: 999 }];
    var newArr = [];
    var num = 0;
    //获取到pathKey下与apple数组对应的值
    for(let i=0;i<pathKey.length;i++){
        if(i == num){
            newArr = apple[pathKey[i]];
        }else if(i>num){
            newArr = newArr.children[pathKey[i]];
            //在找到最后一个节点的时候添加一个子对象
            if(i == pathKey.length-1 ){
                newArr.children = arr;
                console.log(newArr)
            }
        }
        num = i;   
    }
})()
0
var arr = [{ name: 999 }];
function loop(apple,arr){
 for(var x=0;x<pathKey.length;x++){
     var child = apple[[pathKey[x]]];
    if(child){ //继续访问索引
       if(child.children && child.children.length>0){ 
        loop(child.children,arr);
         break;
       }else //索引完没有children属性时赋值
         x==arr.length&&(child.children = arr);
    }
  }
}
loop(apple,arr);

撰写答案

推广链接