如何从对象的输入数组中获得所需的对象数组? -JavaScript

时间:2019-04-17 18:14:42

标签: javascript

在输入的对象数组中,我有一个名为“坡度”的字段,并且有一个名为“厚度”的字段。如果在特定对象中,如果“坡度”和“厚度”相同,则应添加其“数量”。等级AU27和厚度5.00有两个数量(2.00和17.00)。因此,我们创建了一个字段Thickness5Qty值应为(2.00和17.00)

与等级FE500D类似,共有3种厚度,因此将创建“厚度10”,“厚度12”和“厚度8”字段。

 var input = [
 {
  "Qty": "2.00",
  "Grade": "AU27",
  "Thickness": "5.00",
 },
 {
  "Qty": "7.00",
  "Grade": "AU27",
  "Thickness": "10.00",
 },
 {
  "Qty": "17.00",
  "Grade": "AU27",
  "Thickness": "5.00",
 },
 {
  "Qty": "51.00",
  "Grade": "FE500D",
  "Thickness": "10.00",
 },
 {
  "Qty": "69.00",
  "Grade": "FE500D",
  "Thickness": "12.00",
 },
 {
  "Qty": "30.00",
  "Grade": "FE500D",
  "Thickness": "8.00",
 },
 {
  "Qty": "92.00",
  "Grade": "FE500D",
  "Thickness": "10.00",
  }
];

我想要的结果

 var output = [
  {
    "Grade": "AU27",
"Thickness5Qty": "19.00",// sum of all Grade - AU27 Quantities where Thickness is 5 (1st and 3rd objects quantities merged)
"Thickness10Qty": "7.00",
  },
  {
   "Grade": "FE500D",
   "Thickness10": "143.00",//sum of Grade-FE500D where Thickness is 10
"Thickness12": "69.00",
"Thickness8": "30.00"
   }
 ];

如何从对象的输入数组中获取对象的输出数组?

更新的问题-新字段所需的总数

我想要的结果

 var output = [
  {
    "Grade": "AU27",
"Thickness5Qty": "19.00",// sum of all Grade - AU27 Quantities where Thickness is 5 (1st and 3rd objects quantities merged)
"Thickness10Qty": "7.00",
"TotalQty": "26.00"
  },
  {
   "Grade": "FE500D",
   "Thickness10Qty": "143.00",//sum of Grade-FE500D where Thickness is 10
"Thickness12Qty": "69.00",
"Thickness8Qty": "30.00",
"TotalQty": "242.00"
   }
 ];

1 个答案:

答案 0 :(得分:3)

您可以使用Array#reduce方法创建键值配对的分组对象,并使用Object.values方法提取分组的对象值。

var input = [{"Qty":"2.00","Grade":"AU27","Thickness":"5.00"},{"Qty":"7.00","Grade":"AU27","Thickness":"10.00"},{"Qty":"17.00","Grade":"AU27","Thickness":"5.00"},{"Qty":"51.00","Grade":"FE500D","Thickness":"10.00"},{"Qty":"69.00","Grade":"FE500D","Thickness":"12.00"},{"Qty":"30.00","Grade":"FE500D","Thickness":"8.00"},{"Qty":"92.00","Grade":"FE500D","Thickness":"10.00"}];

          // extract values from object
let res = Object.values(input.reduce((obj, { Grade, Thickness, Qty }) => { // extract all values
  // convert thickness to number
  Thickness = +Thickness;
  // key for sum
  let key = `Thickness${Thickness}Qty`;
  // define object correspoding to grade if not defined
  obj[Grade] = obj[Grade] || { Grade , TotalQty : 0 };      
  // define sum correspoding to grade key if not defined
  obj[Grade][key] = obj[Grade][key] || 0;
  // add to existing sum
  obj[Grade][key] += +Qty; // if you want sum with two fractional points then obj[Grade][key] = (+obj[Grade][key] + +Qty).toFixed(2)
  // add with total
  obj[Grade].TotalQty += +Qty;  
  // return object reference   
  return obj;
// set initial value as empty object
}, {}));

console.log(res)