如何在 Strapi v3 中制作多级(嵌套)类别?

如何正确构建嵌套的类别列表,以便可以在前端使用它与 <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"
      }
    ]
  }
]

有什么解决方案,或者有人可以用一个想法来启动我吗?

stack overflow How to make multi-level (nested) categories in Strapi v3?
原文答案
author avatar

接受的答案

所以我想出了以下解决方案:

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;
}

答案: