我想生成一个objects of objects, who also contain objects, 基于WPcategories/subcategories

I want to generate an object of objects, who also contain objects, based on WP categories/subcategories

我一直在使用 WP REST Api 将应用程序迁移到无头 wp + React 应用程序,但在 WP 显示 Cats 和 SubCats 的方式上遇到了一些问题。

我的想法是获取所有当前类别并根据父类别生成子类别,这些子类别也可以得到子类别,因为WP cat-subcat结构是无限的。

Category { SubCategory { SubCategory {infinite}}}

我一直在尝试生成一个包含此信息的新对象并以不同的方式进行迭代,例如推送 'parentId' 等于父亲 ID 的对象,但不断得到未定义。

我现在的逻辑是这样的:

const fatherCategories = categories.filter((item) => (
   item.parent === 0
))

const subCategories = categories.filter((item) => (
   item.parent !== 0
))

const subCategories = subCats.forEach((category) => (
   subCats.filter((item) => (
      category.id === item.parent
   ))
))

我 100% 确定这不是我获得 objective 所需的方式,但我的知识到此为止,无法为这个问题找到任何解决方案,如果我知道子类别的长度,我会走另一条路,但没有这个数据,我被阻止了。

正如我之前的评论所说,这样的东西应该适合你:

function isParent(category) {
  return category.parent === 0;
}

function findAllchildren(allCategories, currentCategory) {
  // const allCategories.filter()
  const currCatChildren = allCategories.filter(
    (c) => c.parent === currentCategory.id
  );
  if (currCatChildren.length) {
    currCatChildren.forEach((c) => {
      c.children = findAllchildren(allCategories, c);
    });
  }
  return currCatChildren;
}

const categories = [
  { id: 1, parent: 0, name: "pc -> 1" },
  { id: 2, parent: 0, name: "pc -> 2" },
  { id: 3, parent: 1, name: "cc -> 3>1" },
  { id: 4, parent: 2, name: "cc -> 4>2" },
  { id: 5, parent: 3, name: "cc -> 5>3" },
  { id: 6, parent: 4, name: "cc -> 6>4>1" },
  { id: 7, parent: 5, name: "cc -> 7>5>3>1" },
];

const finalCategoryTree = categories.filter(isParent).map((parentCategory) => {
  const tmp = { ...parentCategory };
  tmp.children = findAllchildren(categories, parentCategory);
  return tmp;
});

console.log(JSON.stringify(finalCategoryTree));