2017-05-01 3 views
0

나는이 같은 목적을했습니다 : 내가보기에 같은 개체를 나열 할깊은 중첩 된 객체를 분류하는 방법은 무엇입니까?

var list = [ 
    { 
     category:'CATEGORY 1', 
     label:'Item 1', 
     children:[{ 
      category:'CATEGORY 2', 
      label:'Item 1', 
      children:[] 
     },{ 
      category:'CATEGORY 2', 
      label:'Item 2', 
      children:[{ 
       category:'CATEGORY 3', 
       label:'Item 1', 
       children:[] 
      },{ 
       category:'CATEGORY 3', 
       label:'Item 2', 
       children:[] 
      }] 
     }] 
    }, 
    { 
     category:'CATEGORY 1', 
     label:'Item 2', 
     children:[{ 
      category:'CATEGORY 2', 
      label:'Item 3', 
      children:[] 
     },{ 
      category:'CATEGORY 2', 
      label:'Item 4', 
      children:[{ 
       category:'CATEGORY 3', 
       label:'Item 2', 
       children:[] 
      },{ 
       category:'CATEGORY 3', 
       label:'Item 3', 
       children:[] 
      }] 
     }] 
    } 
    ] 

.

enter image description here

JSON 깊은 몇 가지 단계, 어쩌면 6 각 노드에서 children 8 아래로 이동합니다. javaScript에서 적절한 방법을 찾을 수 없습니다.

각 범주를 분리하고 각 개체를 반복해야합니까?

답변

0

여기서 도움이되는 재귀 함수가 필요합니다. 당신의 모든 범주에 걸쳐

function findCategories(list) { 
    list.forEach(function(item) { 
    // do something with the category and label here 
    console.log(item.category); 

    // does this object have any children? if yes, call find categories again 
    if (item.hasOwnProperty("children")) { 
     findCategories(item.children); 
    } 
    }) 
} 

이 함수의 뜻 루프를하고 children 재산이 있는지 확인 : 이것 좀 봐. 있을 경우 findCategories() 함수를 다시 호출하고 children 배열을 전달하여 동일한 작업을 수행합니다.

아래의 스 니펫에서 실습 예제를 체크 아웃 할 수 있습니다.

var list = [ 
 
    { 
 
     category:'CATEGORY 1', 
 
     label:'Item 1', 
 
     children:[{ 
 
      category:'CATEGORY 2', 
 
      label:'Item 1', 
 
      children:[] 
 
     },{ 
 
      category:'CATEGORY 2', 
 
      label:'Item 2', 
 
      children:[{ 
 
       category:'CATEGORY 3', 
 
       label:'Item 1', 
 
       children:[] 
 
      },{ 
 
       category:'CATEGORY 3', 
 
       label:'Item 2', 
 
       children:[] 
 
      }] 
 
     }] 
 
    }, 
 
    { 
 
     category:'CATEGORY 1', 
 
     label:'Item 2', 
 
     children:[{ 
 
      category:'CATEGORY 2', 
 
      label:'Item 3', 
 
      children:[] 
 
     },{ 
 
      category:'CATEGORY 2', 
 
      label:'Item 4', 
 
      children:[{ 
 
       category:'CATEGORY 3', 
 
       label:'Item 2', 
 
       children:[] 
 
      },{ 
 
       category:'CATEGORY 3', 
 
       label:'Item 3', 
 
       children:[] 
 
      }] 
 
     }] 
 
    } 
 
    ] 
 

 
function findCategories(list) { 
 
    list.forEach(function(item) { 
 
    // do something with the category and label here 
 
    console.log(item.category); 
 

 
    // does this object have any children? if yes, call find categories again 
 
    if (item.hasOwnProperty("children")) { 
 
     findCategories(item.children); 
 
    } 
 
    }) 
 
} 
 

 
findCategories(list)

관련 문제