在我的对象输入数组中,有一个名为 Grade 的字段。这是过滤参数
var input = [
{
"Qty": "2.00",
"Grade": "AU27",
"Thickness": "5.00",
"Width": "1200.00",
},
{
"Qty": "7.00",
"Grade": "AU27",
"Thickness": "10.00",
"Width": "1400.00",
},
{
"Qty": "17.00",
"Grade": "AU27",
"Thickness": "5.00",
"Width": "1700.00",
},
{
"Qty": "51.00",
"Grade": "FE500D",
"Thickness": "10.00",
"Width": "1100.00",
},
{
"Qty": "69.00",
"Grade": "FE500D",
"Thickness": "12.00",
"Width": "1500.00",
},
{
"Qty": "30.00",
"Grade": "FE500D",
"Thickness": "8.00",
"Width": "1800.00",
},
{
"Qty": "92.00",
"Grade": "FE500D",
"Thickness": "10.00",
"Width": "2200.00",
},
{
"Qty": "98.00",
"Grade": "FE600D",
"Thickness": "11.00",
"Width": "2400.00",
},
{
"Qty": "115.00",
"Grade": "FE600D",
"Thickness": "17.00",
"Width": "2600.00",
}
];
我想从上面的输入数组创建名为 sumGradeArray 的对象数组。如果我们考虑不同等级的总数量,不考虑厚度和宽度,则 AU27 等级的总数量为 2.00 + 7.00 + 17.00 = 26.00。
同样,FE500D 等级的总数量为 51.00 + 69.00 + 30.00 + 92.00 = 242.00
同样,FE600D 级的总数量为 98.00 + 115.00 = 213.00
var sumGradeArray = [
{
"Grade": "AU27",
"TotalQty": "26.00",
},
{
"Grade": "FE500D",
"TotalQty": "242.00",
},
{
"Grade": "FE600D",
"TotalQty": "213.00",
},
];
请有人为我提供一个使用 Vanilla JS(无 Jquery/Lodash)的通用解决方案。我在这里只显示了 3 个等级,实际上对象的输入数组是一个 API 响应。它可以有数百个等级
最佳答案
您可以选择 Map
用于对相同等级进行分组并渲染所需的样式。
var input = [{ Qty: "2.00", Grade: "AU27", Thickness: "5.00", Width: "1200.00" }, { Qty: "7.00", Grade: "AU27", Thickness: "10.00", Width: "1400.00" }, { Qty: "17.00", Grade: "AU27", Thickness: "5.00", Width: "1700.00" }, { Qty: "51.00", Grade: "FE500D", Thickness: "10.00", Width: "1100.00" }, { Qty: "69.00", Grade: "FE500D", Thickness: "12.00", Width: "1500.00" }, { Qty: "30.00", Grade: "FE500D", Thickness: "8.00", Width: "1800.00" }, { Qty: "92.00", Grade: "FE500D", Thickness: "10.00", Width: "2200.00" }, { Qty: "98.00", Grade: "FE600D", Thickness: "11.00", Width: "2400.00" }, { Qty: "115.00", Grade: "FE600D", Thickness: "17.00", Width: "2600.00" }],
result = Array.from(
input.reduce((m, o) => m.set(o.Grade, (+(m.get(o.Grade) || 0) + +o.Qty).toFixed(2)), new Map),
([Grade, TotalQty]) => ({ Grade, TotalQty })
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 如何从给定的对象数组中获取这些对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55785190/