javascript - 如何从给定的对象数组中获取这些对象数组?

标签 javascript

在我的对象输入数组中,有一个名为 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/

相关文章:

javascript - 这个数据系列中有什么问题, Highcharts 没有绘制它?

javascript - fullCalendar 自定义事件函数抛出非函数错误

javascript - 如何在javascript中使用递归代码在对象中创建内部对象

asp.net - 如何让子控件正确的 id 到客户端

javascript - 将字符串和变量连接成 Jade 的变量名

javascript - 如何在javascript中构建没有重复的嵌套对象数组

javascript - 我的 window.onscroll 事件不工作

javascript - 方法/函数在 IntelliSense 中显示为变量

javascript - css 菜单或脚本在 ie 上不起作用

javascript - ExtJS 4.1 - 检索嵌套 JSON 的 hasOne 信息