Typescript映射集合



我有这个复杂的模型,我正试图映射。

  • 我有一个数组购物车包含id,名称等
  • 我有一个字典,其中键是一个类型,其值是不同的产品。

我在页面底部添加了一个示例,说明结果应该是什么样子。

我的尝试,但卡住了如何过滤

carts.forEach(cart => {
const productList = cart.products; //list of products
Object.entries(content.data).forEach(([key, values]) => {
const sizeList = values.map(x => x.sizeList); //list of size
// i am stuck here
});
});

const getCartsWithProductNames = (carts = [], content = {}) => {
// create a Map with productId-sizeId as key, and size name as value
const productSizeNameMap = 
Object.values(content)
.flat()
.reduce((map, { productId, sizeList = [] }) => {
sizeList.forEach(({ sizeId, name }) =>
map.set(`${productId}-${sizeId}`, name)
);
return map;
}, new Map);
// return carts list with product items having names from productSizeNameMap
return carts.map(({ cartId, cartName, products = [] }) => ({
id: cartId,
name: cartName,
productItems: products.map(({ id, size, quantity, isVisible }) => ({
id, quantity, isVisible, name: productSizeNameMap.get(`${id}-${size}`)
}))
}));
}
const 
carts = [
{
cartId: 500,
cartName: "Some name",
products: [ { id: 1, size: 10, quantity: 1, isVisible: true }, { id: 2, size: 13, quantity: 10, isVisible: true } ]
}
],
content = {
"Drinks": [
{ productId: 1, sizeList: [ { sizeId: 10, name: "100ml beer" }, { sizeId: 9, name: "200ml beer" } ]
}
],
"Food": [
{
productId: 2,
sizeList: [ { sizeId: 12, name: "6 wings" }, { sizeId: 13, name: "12 wings" } ]
}
]
};
console.log( getCartsWithProductNames(carts, content) );

最新更新