我试图了解 Javascript 数组函数。我有一个像这样的嵌套数组,其中每一行都覆盖相同的时间段:
[{
"category": "fruit",
"variety": "apple",
"data": [{
"day": 1,
"units": 2
}, {"day": 2,
"units": 4
}]
},{
"category": "fruit",
"variety": "orange",
"data": [{
"day": 1,
"units": 3
}, {"day": 2,
"units": 5
}]
},{
"category": "veg",
"variety": "tomato",
"data": [{
"day": 1,
"units": 4
}, {"day": 2,
"units": 2
}]
}]
我想按类别按天对单位求和,以获得这样的数组:
[{
"category": "fruit",
"data": [{
"day": 1,
"units": 5
}, {"day": 2,
"units": 9
}]
},{
"category": "veg",
"data": [{
"day": 1,
"units": 4
}, {"day": 2,
"units": 2
}]
}]
我一直在通过长循环 if 语句来解决这个问题,并对其进行一些散列。你能看到一个优雅的方法来解决这个问题吗?
非常感谢!