Given the index value, dynamically insert child nodes into the parent node, how to change the array

  
  
  
   
  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~
Feb.23,2022

you write a recursive function! It is judged to continue to execute itself as long as there is a children, and insert the data directly until there is no children,.
function diedai (arr) {

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

}


  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);

my method can only add the effects you want to the new array. For reference only

(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;
    //pathKeyapple
    for(let i=0;i<pathKey.length;iPP){
        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;   
    }
})()

var arr = [{ name: 999 }];
function loop(apple,arr){
 for(var x=0;x<pathKey.length;xPP){
     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);
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e36aac-42ead.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e36aac-42ead.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?