I am currently putting together a simple application for inventory management using backbone. I have a table in my database that contains model and quantity; this is the strigify version of the object:
var invt =
[
{
“id”:1,
“model”:”Canon SX230″,
“qty”:10,
“price”:”150.50″
},
{
“id”:2,
“model”:”Canon Rebel T3i”,
“qty”:25,
“price”:”450.50″,
},
{
“id”:3,
“model”:”Canon Rebel T2″,
“qty”:10,
“price”:”250.00″
},
{
“id”:4,
“model”:”Canon Rebel T2i”,
“qty”:15,
“price”:”275.00″
},
{
“id”:5,
“model”:”Canon SX230″,
“qty”:5,
“price”:”125.00″
}]
How can I filter through to sum the quantities based on the model. Creating a new object with the similar models totaled quantity.
Essentially the result would be:
[{
“id”:1,
“model”:”Canon SX230″,
“qty”:15,
“price”:”275.00″
},
{
“id”:2,
“model”:”Canon Rebel T3i”,
“qty”:25,
“price”:”450.50″
}]
etc…
I’ve been trying to use the following loop:
var sum = {};
for (var i = 0; i < invt.length; i++) {
var record = invt[i];
sum.model = record.model + (sum.model);
};
As you’ve used only JS related tags, I guess you want to do this client-side.
You can do it like this:
Demo: http://jsfiddle.net/Dhsm5/
It would be trivial to convert this object into the format you want.