我正在尝试组织一个数组,该数组的重复值(橙色)具有不同的数量值...所以我想合并相似的值并计算数量。
如果我使用水果名称但使用随机名称,我可以做到。
var Orders = [
{Fruit: "Orange", Quantity: 1000},
{Fruit: "Banana", Quantity: 2000},
{Fruit: "Orange", Quantity: 6000}];
var finalOrder = [];
var Quantity = 0;
for (var i in Orders) {
Quantity += Orders[i].Quantity;
var Fruits = Orders[i].Fruit;
var Order = {
Fruit: Fruits,
Quantity: Quantity
}
finalOrder.push(Order);
}
console.log(finalOrder);
我希望输出
0: {Fruit: "Orange", Quantity: 1000}
1: {Fruit: "Banana", Quantity: 3000}
3: {Fruit: "Orange", Quantity: 9000}
成为
0: {Fruit: "Orange", Quantity: 7000}
1: {Fruit: "Banana", Quantity: 2000}
答案 0 :(得分:1)
代码的主要问题是,您对所有数量都使用一个变量,而没有寻找相同的Fruit
。
对于这一部分,您需要另一个循环,如果发现更新Quantity
并退出内部循环,或向结果集中添加新对象。
var orders = [{ Fruit: "Orange", Quantity: 1000 }, { Fruit: "Banana", Quantity: 2000 }, { Fruit: "Orange", Quantity: 6000 }],
finalOrder = [],
i, j;
outer: for (i = 0; i < orders.length; i++) {
for (j = 0; j < finalOrder.length; j++) {
if (orders[i].Fruit === finalOrder[j].Fruit) {
finalOrder[j].Quantity += orders[i].Quantity;
continue outer;
}
}
finalOrder.push({ Fruit: orders[i].Fruit, Quantity: orders[i].Quantity });
}
console.log(finalOrder);
或者您可以采用Map
和简单的键/值方法,因为您只有两个属性可以很好地实现此方法。
var orders = [{ Fruit: "Orange", Quantity: 1000 }, { Fruit: "Banana", Quantity: 2000 }, { Fruit: "Orange", Quantity: 6000 }],
result = Array.from(
orders.reduce((m, { Fruit, Quantity }) => m.set(Fruit, (m.get(Fruit) || 0) + Quantity), new Map),
([Fruit, Quantity]) => ({ Fruit, Quantity })
);
console.log(result);
答案 1 :(得分:0)
简化为以Fruit
索引的对象,该对象的值是关联的水果键的数量,然后获取该对象的值:
var Orders = [{
Fruit: "Orange",
Quantity: 1000
},
{
Fruit: "Banana",
Quantity: 2000
},
{
Fruit: "Orange",
Quantity: 6000
}
];
const output = Object.values(Orders.reduce((a, { Fruit, Quantity }) => {
if (!a[Fruit]) a[Fruit] = { Fruit, Quantity };
else a[Fruit].Quantity += Quantity;
return a;
}, {}));
console.log(output);