【发布时间】:2014-10-29 19:49:00
【问题描述】:
我正在尝试找到最简单的方法来获取具有相似信息的数组并创建带有子数组的数组。新创建的父数组还应该对子数组中找到的值求和。这相当于使用 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
},
]
【问题讨论】:
标签: javascript arrays underscore.js lodash