以树阵列模式

时间:2016-06-08 05:48:19

标签: javascript

我有一个这样的数组:

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: []
}

1 个答案:

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