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

时间:2018-08-15 22:59:11

标签: javascript arrays typescript

我有以下嵌套数组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数组以知道将使用多少个软件包。

1 个答案:

答案 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;
  }

}