重新排列 JSON 个对象

Re-arrange a JSON object

我有来自数据库的数据,如下所示:

[
  {
    ID: 1,
    UPC: 11111,
    Qty: 1,
    Price: 1.99
  },
  {
    ID: 2,
    UPC: 11111,
    Qty: 2,
    Price: 1.99
  },
  {
    ID: 3,
    UPC: 22222,
    Qty: 1,
    Price: 9.99
  },
  {
    ID: 4,
    UPC: 11111,
    Qty: 3,
    Price: 1.99
  },
  {
    ID: 5,
    UPC: 22222,
    Qty: 9,
    Price: 9.99
  }
]

在页面中,如果他们点击了一个按钮,我需要将其重新排列成如下所示:

[
  {
    UPC: 11111,
    Qty: 6,
    Price: 1.99
  },
  {
    UPC: 22222,
    Qty: 10,
    Price: 9.99
  }
]

如何转换? 99% 的时间我需要原始数据集,所以一开始像第二个数据集一样返回它不是一个选项。

TIA。

使用上面评论中发布的link,我成功地完成了这项工作。我觉得使用 Underscore.js 可能是一种更有效的方法,但由于我无法弄清楚,所以可以这样做。

var tmpItems = {};
for (var i = items.length; i--;)
{
  // init an array, if it is not there
  tmpItems[it.All[i]['UPC']] = tmpItems[it.All[i]['UPC']] || [];

  tmpItems[it.All[i]['UPC']]['Qty'] = (tmpItems[it.All[i]['UPC']]['Qty'] || 0) + (it.All[i]['Qty'] || 0);
  tmpItems[it.All[i]['UPC']]['Price'] = (it.All[i]['Price'] || 0);
}

// convert back to an object
var newItems = [];
for (var key in tmpItems)
{
  if (tmpItems.hasOwnProperty(key))
  {
    newItems.push({ 'UPC': key, 'Qty': tmpItems[key]['Qty'], 'Price': tmpItems[key]['Price'] });
  }
}