变更阵列结构

时间:2019-04-11 13:13:05

标签: javascript

我有一个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: []
    },
}]

1 个答案:

答案 0 :(得分: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,
 }));