【发布时间】:2018-12-01 14:11:10
【问题描述】:
我有一个平面 JSON 数组,其中重复了 identifier、categoryId 和 category:
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"
},
]
如何合计每个类别的价格并将对象推入每个类别的末尾,identifieras Total 与总值。我知道将对象推入 JSON 数组最后将对象推入。但这很好,因为我可以像这样使用sort 函数对数组进行排序:
function compare(a,b) {
if (a.categoryId < b.categoryId)
return -1;
if (a.categoryId> b.categoryId)
return 1;
return 0;
}
data.sort(compare);
已编辑
我希望输出是这样的:
: [
{
"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"
}
]
【问题讨论】:
-
你能添加预期的输出吗?
-
@Rahul 我已经更新了预期的输出
标签: javascript arrays json typescript