[英]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.