2016-06-08 4 views
1

У меня есть массив как это:Создать структуру дерева в 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: [] 
     }] 
     }] 
    }] 
    }] 
}]; 
+0

И где вы застряли? Что вы пробовали? –

+0

@FelixKling Я могу просто создать один уровень древовидной структуры. Но теперь с кодом Pranav C Balan, я могу решить проблему. чем вы !! –

ответ

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

Вы можете сделать что-то простое, как это с помощью while loop и Array#splice метод.

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

0

Кажется потенциальным примером использования reduceRight. Вам просто нужно добавить предыдущее значение, как ребенок к следующему значению:

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

Я не вижу причины, чтобы иметь массив на верхнем уровне, но это легко достичь, а также.

Смежные вопросы