我正在尝试使用具有“数量”属性的对象遍历现有数组,并通过控制值重建它。
let cart = [{id: 1, name: 'Pizza', quantity: 5, specialId: 0},
{id: 2, name: 'Burger', quantity: 2, specialId: 0}];
我控制了 3 件商品,即每 3 件商品您可以获得折扣,所以我想按如下方式重构购物车数组:
cart = [{id: 1, name: 'Pizza', quantity: 3, specialId: 1},
{id: 2, name: 'Pizza', quantity: 2, specialId: 2},
{id: 3, name: 'Burger', quantity: 1, specialId: 2},
{id: 4, name: 'Burger', qty: 1, specialId: 0}]
我已经研究了几种实现此目的的方法,主要是围绕创建一个新的单一数量项目数组,然后创建另一个最终数组,但这肯定不是很有效吗?
如果有任何指点,我将不胜感激。我有一种可怕的感觉,我错过了一些简单的东西并且盯着它看了太久。
最佳答案
如果我理解正确的话,三个的数量不知道产品的类型,所以第二批三个(在你的例子中)包含 2 个比萨饼和 1 个汉堡。
specialId
似乎是唯一的,并且对于每个完整的三个集合(其中每个项目都共享该 specialId
值)来说都是非零的,并且对于任何一个都为零剩余项目。
最后,结果中的id
似乎与输入无关,只是一个递增的数字。
这里是你如何做到的:
function splitBy(cart, size) {
const result = [];
let quantity = 0;
let grab = size;
let specialId = 1;
let id = 1;
for (let item of cart) {
for (quantity = item.quantity; quantity >= grab; quantity -= grab, grab = size, specialId++) {
if (result.length && !result[result.length-1].specialId) result[result.length-1].specialId = specialId;
result.push(Object.assign({}, item, {quantity: grab, specialId, id: id++}));
}
if (quantity) result.push(Object.assign({}, item, {quantity, specialId: 0, id: id++}));
grab = size - quantity;
}
return result;
}
const cart = [{id: 1, name: 'Pizza', quantity: 5, specialId: 0},
{id: 2, name: 'Burger', quantity: 2, specialId: 0}];
const result = splitBy(cart, 3)
console.log(result);
关于Javascript 从现有的属性值拆分创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52950596/