当前位置: 代码迷 >> JavaScript >> 如果我不知道类别数组的深度,打印此内容的递归方法是什么
  详细解决方案

如果我不知道类别数组的深度,打印此内容的递归方法是什么

热度:47   发布时间:2023-06-08 09:25:22.0

如果我不知道类别对象的深度,如何打印此代码? 如何在不同情况下将其映射为递归类别?

const category =  [{"id":8,"name":"Genere","parent":null,"category":[]},
{"id":1,"name":"Movies","parent":null,"category":[{
"id":2,"name":"Bollywood","parent":1,"category":[]
},
{"id":3,"name":"Hollywood","parent":1,"category":[]}
]},
{"id":9,"name":"Region","parent":null,"category":[]},
{"id":4,"name":"Songs","parent":null,"category":[{"id":7,"name":"Bollywood","parent":4,"category":[{"id":10,"name":"Arijit singh","parent":7,"category":[]},
{"id":11,"name":"Sonu Nigam","parent":7,"category":[]}]},
{"id":6,"name":"English","parent":4,"category":[]},
{"id":5,"name":"Hindi","parent":4,"category":[]}]
}]
const printCategory = category.map((cat, i) => {
    return (
        console.log(cat.name + " ------> "  + i),
        cat.category.map((c, i) => {
            console.log(c.name + " ------> " + i),
            c.category.map((ca, i) => {
                console.log(ca.name + " ------> " + i)
            })
        })
        )
})
const printCategory = (c, i) => {
   console.log(c.name + " ------> "  + i)
   c.category.map(printCategory);
}
category.map(printCategory);

您可以对每个嵌套类别使用相同的回调。

 const x = ({ name, category }, i) => { console.log(name, i); category.forEach(x); }, category = [{ id: 8, name: "Genere", parent: null, category: [] }, { id: 1, name: "Movies", parent: null, category: [{ id: 2, name: "Bollywood", parent: 1, category: [] }, { id: 3, name: "Hollywood", parent: 1, category: [] }] }, { id: 9, name: "Region", parent: null, category: [] }, { id: 4, name: "Songs", parent: null, category: [{ id: 7, name: "Bollywood", parent: 4, category: [{ id: 10, name: "Arijit singh", parent: 7, category: [] }, { id: 11, name: "Sonu Nigam", parent: 7, category: [] }] }, { id: 6, name: "English", parent: 4, category: [] }, { id: 5, name: "Hindi", parent: 4, category: [] }] }]; category.forEach(x); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

只需使用常规的递归函数,如果category不存在或为空,则返回。

 const category = [{ "id": 8, "name": "Genere", "parent": null, "category": [] }, { "id": 1, "name": "Movies", "parent": null, "category": [{ "id": 2, "name": "Bollywood", "parent": 1, "category": [] }, { "id": 3, "name": "Hollywood", "parent": 1, "category": [] } ] }, { "id": 9, "name": "Region", "parent": null, "category": [] }, { "id": 4, "name": "Songs", "parent": null, "category": [{ "id": 7, "name": "Bollywood", "parent": 4, "category": [{ "id": 10, "name": "Arijit singh", "parent": 7, "category": [] }, { "id": 11, "name": "Sonu Nigam", "parent": 7, "category": [] } ] }, { "id": 6, "name": "English", "parent": 4, "category": [] }, { "id": 5, "name": "Hindi", "parent": 4, "category": [] } ] } ] function recursiveLoop(array) { if (!array) return; array.forEach(item => { console.log(item.name); recursiveLoop(item.category) }) } recursiveLoop(category); 

  相关解决方案