My JSON looks like this:
json = [
{
type: \"big\"
date: \"2012-12-08\"
qty: 6
}
{
type: \"small\"
date: \"2012-12-08\"
qty: 9
}
This is easily handled by creating a custom object that has properties named with your unique combinations (i.e. type + first 7 of date).
Loop through your array and check if your "holder" object has an existing property named with your unique identifier. If it has the property already, then increment the quantity, otherwise add a new item.
After the holder is completely built, clear your array, then loop through the properties of the holder and push them back on to your array.
var holder = {};
var json = [
{
type: "big",
date: "2012-12-08",
qty: 6
},
{
type: "small",
date: "2012-12-08",
qty: 9
},
{
type: "big",
date: "2012-12-15",
qty: 4
},
{
type: "small",
date: "2012-12-07",
qty: 7
},
{
type: "small",
date: "2012-11-07",
qty: 3
}
];
json.forEach(function(element) {
var identifier = element.type + element.date.slice(0, 7);
if (holder[identifier]) {
holder[identifier].qty += element.qty;
} else {
holder[identifier] = element;
};
});
json = [];
for(var identifier in holder) {
json.push(holder[identifier]);
}
console.log(json);