我有一个这样的数组:
Javascript代码:
var data = [{
name: 'hello',
image: '',
children: [{
name: 'hello2',
image: '',
children: [{
name: 'hello3',
image: '',
children: [{
name: 'hello4',
image: '',
children: [{
name: 'hello5',
image: '',
children: []
}]
}]
}]
}]
}];
我想将此数组添加到最后一个孩子
{
name: 'hello6',
image: '',
children: []
}
答案 0 :(得分:0)
您可以使用while loop执行此类操作。
var data = [{
name: 'hello',
image: '',
children: [{
name: 'hello2',
image: '',
children: [{
name: 'hello3',
image: '',
children: [{
name: 'hello4',
image: '',
children: [{
name: 'hello5',
image: '',
children: []
}]
}]
}]
}]
}];
// variable to store the inner object reference
var obj = data[0],
// element to push the array
ele = {
name: 'hello6',
image: '',
children: []
};
// iterate upto getting an empty children array object
while (obj.children.length) {
// update reference to the inner object
obj = obj.children[0];
}
// push it to the inner object property
obj.children.push(ele);
console.log(data);