2017-07-24 48 views
0

我有一些像這樣的數據(簡化):我該如何去「總結」這樣的對象數組?

sales: [ 
    { 
     'quantity': 20, 
     'amount': 40, 
     'product': { 
      'id': 1 
      'category': 'Chemical', 
      'subcategory': 'Herbicide' 
     } 
    }, 
    { 
     'quantity': 10, 
     'amount': 70, 
     'product': { 
      'id': 1 
      'category': 'Chemical', 
      'subcategory': 'Herbicide' 
     } 
    }, 
    { 
     'quantity': 30, 
     'amount': 60, 
     'product': { 
      'id': 2 
      'category': 'Seed', 
      'subcategory': 'Corn' 
     } 
    } 
] 

我希望將我的數據由product.id,總結了quantityamount並保持相同的categorysubcategory(這將是所有相同的同產品的ID)

所以基本上我希望我的數據是這樣的:

filteredSum: [ 
    { 
     'quantity': 30, 
     'amount': 110, 
     'product': { 
      'category': 'Chemical', 
      'subcategory': 'Herbicide' 
     } 
    }, 
    { 
     'quantity': 30, 
     'amount': 60, 
     'product': { 
      'category': 'Seed', 
      'subcategory': 'Corn' 
     } 
    } 
] 

我使用Lodash,這是什麼我想出了一些東西,但是有些東西告訴我有一個更簡潔的方法來做到這一點?

filteredSum: function() { 
    return _(this.sales).groupBy('product.id').map(function (sales) { 
     return { 
      'quantity': _.sumBy(sales, function(sale) { return Number(sale.quantity); }).toFixed(2), 
      'amount': _.sumBy(sales, function(sale) { return Number(sale.amount); }), 
      'product': { 
       'category': _.head(sales).product.category, 
       'subcategory': _.head(sales).product.subcategory 
      } 
     } 
    }).value(); 
} 

當然有更好的辦法嗎?

+0

如果你可以使用箭頭功能,'函數(銷售){回報號碼(sale.quantity); ''成爲'銷售 - >號碼(sale.quantity)''。這有點簡潔。 – Amy

+0

不幸的是,我不能在這個項目中使用ES2015,因爲JavaScript沒有通過任何構建工具運行。 –

+0

是'quantity'和'amount'某種相關的? –

回答

3

最簡單的方法是將對象與productId作爲主鍵。然後只需使用reduce來迭代你的數組。如果當前產品的productId已經存在,只需將其值與前一個值相加,否則將其添加到該對象。

const data = [ 
 
    { 
 
    'quantity': 20, 
 
    'amount': 40, 
 
    'product': { 
 
     'id': 1, 
 
     'category': 'Chemical', 
 
     'subcategory': 'Herbicide' 
 
    } 
 
    }, 
 
    { 
 
    'quantity': 10, 
 
    'amount': 70, 
 
    'product': { 
 
     'id': 1, 
 
     'category': 'Chemical', 
 
     'subcategory': 'Herbicide' 
 
    } 
 
    }, 
 
    { 
 
    'quantity': 30, 
 
    'amount': 60, 
 
    'product': { 
 
     'id': 2, 
 
     'category': 'Seed', 
 
     'subcategory': 'Corn' 
 
    } 
 
    } 
 
]; 
 

 
const result = data.reduce((acc, curr) => { 
 
    if (acc[curr.product.id]) { 
 
    acc[curr.product.id].quantity += curr.quantity; 
 
    acc[curr.product.id].amount += curr.amount; 
 
    } else { 
 
    acc[curr.product.id] = curr; 
 
    } 
 
    
 
    return acc; 
 
}, {}); 
 

 
const formatedResult = Object.keys(result).map(entry => { 
 
    return result[entry]; 
 
}); 
 

 
console.log(formatedResult);

+0

謝謝,蕾!正是我在找什麼。 –

+0

問題:爲什麼reduce會返回對象而不是對象數組?任何方式讓它做後者? –

+1

@RyanMortier答案更新,以返回一個數組:) – Erazihel