0
我試圖找到最簡單的方法來獲取具有信息的數組,並創建一個數組與子數組。新創建的父數組也應該求和在子數組中找到的值。這相當於使用sum/group by的SQL語句。與子陣列的組數組
這是原來的陣列
[
{
'userId':1,
'userName':'bob',
'category':'shoes',
'count':2
},
{
'userId':1,
'userName':'bob',
'category':'rocks',
'count':4
},
{
'userId':1,
'userName':'bob',
'category':'bags',
'count':3
},
{
'userId':2,
'userName':'sue',
'category':'shoes',
'count':1
},
{
'userId':2,
'userName':'sue',
'category':'rocks',
'count':7
},
{
'userId':2,
'userName':'sue',
'category':'bags',
'count':4
},
]
這就是我想要的新創建的數組的樣子:
[
{
'userId':1,
'userName':'bob',
'purchases': [
{'category':'shoes','count':'2'},
{'category':'rocks','count':'4'},
{'category':'bags','count':'3'}
],
'totalCount' : 9
},
{
'userId':2,
'userName':'sue',
'purchases': [
{'category':'shoes','count':'1'},
{'category':'rocks','count':'7'},
{'category':'bags','count':'4'}
],
'totalCount' : 12
},
]