2017-05-01 6 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)

関連する問題