我有一个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: []
},
}]
您可以在映射时直接执行此操作:
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,
}));