Bryan Fritchie Bryan Fritchie -4 years ago 123
Javascript Question

Re-arrange a JSON object

I have data that comes from the database looking like:

[
{
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
}
]


Within the page, if they click a button, I need to rearrange it to look like this:

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


How can I convert this? 99% of the time I need the original dataset, so initially returning it like the 2nd dataset is not an option.

TIA.

Answer Source

Using the link posted above in the comments, I managed to make this work. I feel like there is probably a more efficient way using Underscore.js, but since I can't figure it out, this will do.

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'] });
  }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download