簡體   English   中英

根據“類別”屬性減少對象數組,並對“金額”屬性求和

[英]Reduce array of objects based on “category” property and sum “amount” property

我有一個這樣的JSON對象:

balance = [{category:"clothing", amount:"120.50"}, {category:"groceries", amount:"145.23"}, {category:"clothing", amount:"97.34"}];

我想將其簡化為以下形式:

merged_totals = [{category:"clothing", amount:"217.84"}, {category:"groceries", amount:"145.23"}]

這是我目前正在使用的代碼,它很簡單,但是沒有按需要設置對象的格式,如上所示:

combineCategories = function (data) {

  var newData = [];

  for (var prop in data) {
    newData[ data[prop].category ] = 0; // set initial value otherwise it will be undefined
  }

  for (var prop in data) {
    newData[ data[prop].category ] += +data[prop].amount;
  }

  console.log(newData);

}

返回:

// [Clothing: 195, Groceries: 140, Deposit: 995.6] 
var balance = [
  {category: "clothing", amount:"120.50"}, 
  {category: "groceries", amount:"145.23"}, 
  {category: "clothing", amount:"97.34"}
];

var combineCategories = function (data) {
  var res = {};

  data.forEach(function (el) {
    res[el.category] = (res[el.category]) 
      ? res[el.category] += +el.amount 
      : +el.amount;
  });

  return Object.keys(res).map(function (el) {
    return {category: el, amount: res[el]};  
  });
}

console.log(combineCategories(balance));

http://jsbin.com/neqeli/2/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM