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