I have an flat JSON array where identifier, categoryId and category are repeated:
data: [
{
"identifier": "data",
"categoryId": "1",
"category": "Baked goods",
"product": "Aunt Hattie's",
"price": "375"
},
{
"identifier": "data",
"categoryId": "1",
"category": "Baked goods",
"product": "Back to Nature",
"price": "343"
},
{
"identifier": "data",
"categoryId": "2",
"category": "Cakes",
"product": "Mars Muffin (McVitie's)",
"price": "465"
},
{
"identifier": "data",
"categoryId": "2",
"category": "Cakes",
"product": "McVitie's",
"price": "251"
},
{
"identifier": "data",
"categoryId": "2",
"category": "Cakes",
"product": "Mr Kipling",
"price": "260"
},
{
"identifier": "data",
"categoryId": "2",
"category": "Cakes",
"product": "Mr Kipling Frosty Fancies",
"price": "210"
},
{
"identifier": "data",
"categoryId": "3",
"category": "Dairy products",
"product": "Amul",
"price": "474"
},
{
"identifier": "data",
"categoryId": "3",
"category": "Dairy products",
"product": "Borden",
"price": "184"
},
{
"identifier": "data",
"categoryId": "3",
"category": "Dairy products",
"product": "Broughton Foods Company",
"price": "43"
},
]
How can I total the price of each category and push the object into the end of each category and identifieras Total with the total value. I know pushing the object into JSON array push the object at the end. But that is quite fine because I can sort the array by using sort function like this:
function compare(a,b) {
if (a.categoryId < b.categoryId)
return -1;
if (a.categoryId> b.categoryId)
return 1;
return 0;
}
data.sort(compare);
EDITED
I want the output to be like this:
: [
{
"identifier": "data",
"categoryId": "1",
"category": "Baked goods",
"product": "Aunt Hattie's",
"price": "110"
},
{
"identifier": "data",
"categoryId": "1",
"category": "Baked goods",
"product": "Back to Nature",
"price": "344"
},
{
"identifier": "Total",
"categoryId": "1",
"category": "Baked goods",
"price": "454"
},
{
"identifier": "data",
"categoryId": "2",
"category": "Cakes",
"product": "Mars Muffin (McVitie's)",
"price": "455"
},
{
"identifier": "data",
"categoryId": "2",
"category": "Cakes",
"product": "Secret Recipe",
"price": "471"
},
{
"identifier": "data",
"categoryId": "2",
"category": "Cakes",
"product": "Vimto Jam Tarts",
"price": "235"
},
{
"identifier": "Total",
"categoryId": "2",
"category": "Cakes",
"price": "1161"
},
{
"identifier": "data",
"categoryId": "3",
"category": "Dairy products",
"product": "Alta Dena",
"price": "158"
},
{
"identifier": "data",
"categoryId": "3",
"category": "Dairy products",
"product": "Chivers",
"price": "399"
},
{
"identifier": "Total",
"categoryId": "3",
"category": "Dairy products",
"price": "557"
}
]