我有以下嵌套数组products
:
products: [
[{
Variant: {
variant_id: '1',
weight: 15
},
Product: {
_id: '1',
_shop_id: '1'
},
quantity: 5,
totalPrice: 600
}],
[{
Variant: {
variant_id: '2',
weight: 20
},
Product: {
_id: '2',
_shop_id: '2'
},
quantity: 4,
totalPrice: 500
},
{
Variant: {
variant_id: '5',
weight: 25
},
Product: {
_id: '3',
_shop_id: '2'
},
quantity: 3,
totalPrice: 400
}
]
]
我有一个packages
数组,需要用package
个对象填充。规则:包装中必须装有相同_shop_id
的产品(明白了),并且产品总和不得超过30kg的极限重量。换句话说,如果Variant.weight
的总和超过30,则需要添加一个新包。例如,products
数组需要三个包:
// Package 1 - weight: 15kg - shopId: 1
{Variant: {variant_id: '1', weight: 15}, Product: {_id: '1', _shop_id:'1'}, quantity: 5, totalPrice: 600}
// Package 2 - weight: 20kg - shopId: 2
{Variant: {variant_id: '2', weight: 20}, Product: {_id: '2', _shop_id:'2'}, quantity: 4, totalPrice: 500}
// Package 3 - Needs new package because it would be 45kg - weight: 25kg - shopId: 2
{Variant: {variant_id: '5', weight: 25}, Product: {_id: '3', _shop_id:'2'}, quantity: 3, totalPrice: 400}
我只需要知道包装所有产品需要多少包装。 package
对象将在一个软件包充满后添加,如下所示:
export interface Package {
weight: number;
}
export class CartComponent {
someMethod() {
let packages: Package[] = [];
let weight = 0;
products.forEach(prod =>
{
while(weight < 30) {
weight += prod.Variant.weight;
let package = { weight: weight };
}
packages.push(package);
}
});
}
}
我做错了什么?我需要正确循环products
数组以知道将使用多少个软件包。
答案 0 :(得分:1)
请记住,您有一个数组数组。在外部阵列上调用forEach
时,您会从一家商店获得内部产品阵列。然后,您必须以某种方式遍历内部数组。我建议使用forEach
而不是while
。以下几个简单的测试对我有用:
export class CartComponent {
someMethod() {
let packages: Package[] = [];
let weight = 0;
let finishPackage = () => {
packages.push({ weight: weight });
weight = 0;
};
products.forEach(sameShopProducts =>
{
sameShopProducts.forEach(prod => {
if (weight + prod.Variant.weight > 30) {
finishPackage();
}
weight += prod.Variant.weight;
});
// Different shops cannot share a package.
finishPackage();
});
return packages;
}
}