2017-12-25 16 views
2

다음 데이터가 있습니다.자바 스크립트에서 중첩 배열을 중첩 배열로 변환하는 방법은 무엇입니까?

[ 
    {"no":1, "name":"ELECTRONICS", "depth":0}, 
    {"no":2, "name":"TELEVISIONS", "depth":1}, 
    {"no":3, "name":"TUBE", "depth":2}, 
    {"no":4, "name":"LCD", "depth":2}, 
    {"no":5, "name":"PLASMA", "depth":2}, 
    {"no":6, "name":"PORTABLE ELECTRONICS", "depth":1}, 
    {"no":7, "name":"MP3 PLAYERS", "depth":2}, 
    {"no":8, "name":"FLASH", "depth":3}, 
    {"no":9, "name":"CD PLAYERS", "depth":2}, 
    {"no":10, "name":"2 WAY RADIOS", "depth":2} 
] 

아래와 같은 데이터를 얻고 싶습니다.

[ 
    { 
     "no":1, 
     "name":"ELECTRONICS", 
     "depth":0, 
     "child_nodes":[ 
      { 
       "no":2, 
       "name":"TELEVISIONS", 
       "depth":1 
       "child_nodes":[ 
        { 
         "no":3, 
         "name":"TUBE", 
         "depth":2 
        }, 
        ... 
       ] 
      }, 
      { 
       "no":6, 
       "name":"PORTABLE ELECTRONICS", 
       "depth":1 
       "child_nodes":[ ... ] 
      } 
     ] 
    } 
] 

저는 재귀 적으로 시도하고 있지만 좋지 않습니다. 바벨을 사용하고 있기 때문에 자바 스크립트의 새로운 기능에는 큰 제한이 없습니다. 좋은 생각이 있다면 알려주세요. 감사!

+1

이'특정에'depth' 연관되어야한다 parent' – charlietfl

답변

6

수준에 대해 도우미 배열을 사용할 수 있습니다.

var array = [{ no: 1, name: "ELECTRONICS", depth: 0 }, { no: 2, name: "TELEVISIONS", depth: 1 }, { no: 3, name: "TUBE", depth: 2 }, { no: 4, name: "LCD", depth: 2 }, { no: 5, name: "PLASMA", depth: 2 }, { no: 6, name: "PORTABLE ELECTRONICS", depth: 1 }, { no: 7, name: "MP3 PLAYERS", depth: 2 }, { no: 8, name: "FLASH", depth: 3 }, { no: 9, name: "CD PLAYERS", depth: 2 }, { no: 10, name: "2 WAY RADIOS", depth: 2 }], 
 
    result = [], 
 
    levels = [{ children: result }]; 
 

 
array.forEach(function (o) { 
 
    levels[o.depth].children = levels[o.depth].children || []; 
 
    levels[o.depth].children.push(levels[o.depth + 1] = o); 
 
}); 
 

 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

+2

이것은 정말 간단합니다. 이것은 단순히 굉장합니다. –

+0

좋은 아이디어! 고마워. –

1
//The trees root = our expected result 
const result = []; 
var acc = { depth: -1, children: result}; 

for(const el of data){ 
    //walk upwards in the tree 
    var up = acc.depth - el.depth + 1 ; 
    while(up--){ acc = acc.parent } 
    //walk down and add the current el as a child 
    el.parent = acc; 
    (acc.children || (acc.children = [])).push(el); 
    acc = el; 
} 

console.log(result); 

부모님/자녀를 함께 나무를 걸을 수 있습니다.

+0

[그것을보십시오!] (http://jsbin.com/kibahevuha/edit?console) –

+0

를 그것은 도움이되었습니다 많이. 감사!! –