在JavaScript数组中创建树结构

时间:2016-06-08 04:04:12

标签: javascript

我有一个这样的数组:

var data = [
     {name:'hello',image:'',children:[]},
     {name:'hello2',image:'',children:[]},
     {name:'hello3',image:'',children:[]},
     {name:'hello4',image:'',children:[]}
];

我想转换成这个:

var data = [{
  name: 'hello',
  image: '',
  children: [{
    name: 'hello2',
    image: '',
    children: [{
      name: 'hello3',
      image: '',
      children: [{
        name: 'hello4',
        image: '',
        children: [{
          name: 'hello5',
          image: '',
          children: []
        }]
      }]
    }]
  }]
}];

3 个答案:

答案 0 :(得分:1)

可以使用简单的for循环来完成。

var data = [
     {name:'hello',image:'',children:[]},
     {name:'hello2',image:'',children:[]},
     {name:'hello3',image:'',children:[]},
     {name:'hello4',image:'',children:[]}
];

for(var i=0; i<data.length-1; i++){
    var currentData= data[i];
    currentData.children.push(data[i+1]);
}
data.splice(1, data.length);

答案 1 :(得分:0)

您可以使用while loop Array#splice 方法执行此类简单操作。

&#13;
&#13;
var data = [{
  name: 'hello',
  image: '',
  children: []
}, {
  name: 'hello2',
  image: '',
  children: []
}, {
  name: 'hello3',
  image: '',
  children: []
}, {
  name: 'hello4',
  image: '',
  children: []
}];

// variable to hold the inner object
var obj = data[0];

// iterate upto array become only one element
while (1 < data.length) {
  // push to children array the next array element
  obj.children.push(data.splice(1, 1)[0])
  // update obj with reference of inner object
  obj = obj.children[0];
}

console.log(data);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

似乎是reduceRight的潜在用例。您只需将以前的值作为子项添加到下一个值:

data = data.reduceRight((previous, current) => (current.children.push(previous), current));

我没有理由在最高级别拥有阵列,但也很容易实现。