改变数组结构

问题描述 投票:-1回答:1

我有一个categoriesWithSub数组有一个category对象和subCategory对象数组具有以下结构:

[{
    category: {},
    subCategory: [] // The array of subCategories for this category.
}]

这是设置categoriesWithSub数组的代码:

const categories = await getCategories();
const subCategories = await Promise.all(categories.map(category => getSubCategories(category.id)));
const categoriesWithSub = zipWith(categories, subCategories, (category, subCategory) => ({
  category,
  subCategory,
}));

如何根据以下结构更新代码以组合类别和子类别:

[{
    category: {
       id: '',
       catName: '',
       subCategories: []
    },
}]
javascript
1个回答
0
投票

您可以在映射时直接执行此操作:

 const categories = await getCategories();

 const result = await Promise.all(categories.map(async category => {
  const subCategories = await getSubCategories(category.id);
  return { ...category, subCategories };
}));

或者保持你的zipWith

 const result = zipWith(categories,  subCategories, (category, subCategories) => ({
   ...category,
   subCategories,
 }));
© www.soinside.com 2019 - 2024. All rights reserved.