簡體   English   中英

如何對深層嵌套對象進行分類?

[英]How to categorize deep nested object?

我有這樣的反對:

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:[]
            }]
        }]
    }
    ]

我想像視圖中一樣列出對象。

在此處輸入圖片說明

JSON將深入到幾個步驟,也許6-8 children的每個節點。 我無法在javaScript找到執行此操作的適當方法。

我是否需要將每個類別分別拆分並遍歷每個對象?

看起來您需要遞歸函數來幫助您。 看看這個:

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) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM