如何正确构建嵌套的类别列表,以便可以在前端使用它与 <select>
框元素?
集合类型“类别”具有以下字段:
- 类别.id
- 类别.名称
- 类别.类别
处理程序在 /api/categories/controllers/categories.js
中:
async nested(ctx) {
let entities = await strapi.services.categories.find(ctx.query);
const cleaned = entities.map(entity => {
const item = sanitizeEntity(entity, { model: strapi.models.categories });
return item;
})
return nestChilds(cleaned);
}
function nestChilds (object) {
const list = [];
object.forEach(i => {
console.log('LIST:', list);
if (!i.parent) {
list.push(i);
} else {
const parent = list.find(x => x.id === i.parent.id);
parent.childs = [];
parent.childs.push(i);
}
})
return list;
}
但它不起作用。我想要一些这样的结果:
[
{
id: 1,
name: "Top-level category",
childs: [
{
id: 2,
name: "2nd level category 1"
},
{
id: 3,
name: "2nd level category 2",
childs: [
{
id: 5,
name: "3rd level category 1"
}
]
},
{
id: 4,
name: "2nd level category 3"
}
]
}
]
有什么解决方案,或者有人可以用一个想法来启动我吗?