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