提问人:aspirinemaga 提问时间:2/5/2021 最后编辑:aspirinemaga 更新时间:1/23/2022 访问量:2101
如何在 Strapi v3 中制作多级(嵌套)类别?
How to make multi-level (nested) categories in Strapi v3?
问:
如何正确构建类别的嵌套列表,以便可以在带有框元素的前端使用它?<select>
集合类型“类别”包含以下字段:
- categories.id
- categories.name
- 类别.类别
处理程序位于:/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"
}
]
}
]
有什么解决方案,或者有人可以给我一个想法?
答:
2赞
aspirinemaga
2/5/2021
#1
因此,我想出了以下解决方案:
function nestChilds (object) {
const list = [];
object.forEach(i => {
// If is related to parent
if (i.parent) {
// Scope that parent
const parent = object.find(({ id }) => id === i.parent.id);
// Add a child array property to that parent if not already done
if (!parent.hasOwnProperty('childs')) parent.childs = [];
// Add current item to it's corresponding parent
parent.childs.push(i);
// Remove parent property
delete i.parent;
} else {
list.push(i);
}
})
return list;
}
评论