gpt4 book ai didi

javascript - 如何在数组对象的嵌套数组的条件上使用 While 循环?

转载 作者:行者123 更新时间:2023-12-03 01:18:37 25 4
gpt4 key购买 nike

我有以下嵌套数组产品:

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 数组以了解将使用多少个包。

最佳答案

记住,你有一个数组的数组。当您对外部数组调用 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;
}

}

关于javascript - 如何在数组对象的嵌套数组的条件上使用 While 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51867548/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com