我的json看起来像
[
{t_id :"1", val1 : "1" , title:"cash to purchase", unit :"bag"},
{t_id :"1" ,val1 : "1" , title:"cash to purchase", unit :"bag"}
{t_id :"1",val1 : "1" , title:"cash to purchase", unit :"bag"}
{t_id :"2",val1 : "4" , title:"offload", unit :"bag"},
{t_id :"2",val1 : "5" , title:"onroad", unit :"bag"},
{t_id :"3", val1 : "5" , title:"Onroad", unit :"bag"},
{t_id :"3", val1 : "6" , title:"Onroad", unit :"bag"},
]
我想按T_ID进行分组,并根据每个T_ID找到Val1的总和。
标题:购买现金
包:3
标题:卸载
包:9
标题:Onroad
包:11
您去这里。端到端完整解决方案:
var array = [{t_id:"1",val1:"1",title:"cash to purchase",unit:"bag"},{t_id:"1",val1:"1",title:"cash to purchase",unit:"bag"},{t_id:"1",val1:"1",title:"cash to purchase",unit:"bag"},{t_id:"2",val1:"4",title:"offload",unit:"bag"},{t_id:"2",val1:"5",title:"onroad",unit:"bag"},{t_id:"3",val1:"5",title:"Onroad",unit:"bag"},{t_id:"3",val1:"6",title:"Onroad",unit:"bag"}];
var grouped = [];
array.forEach(function(o) {
if (!this[o.t_id]) {
this[o.t_id] = {
t_id: o.t_id,
val1: 0,
title: o.title
};
grouped.push(this[o.t_id]);
}
this[o.t_id].val1 += Number(o.val1);
}, Object.create(null));
console.log(grouped);
$scope.results = grouped;
将下面的代码复制到您的html:
<ion-content>
<ion-list>
<ion-item class="" ng-repeat="result in results">
<div class="item item-text-wrap">
Title: {{result.title}}
<br>
Bag: {{result.val1}}
</div>
</ion-item>
</ion-list>
</ion-content>
制作一个新对象,以存储所有value
W.R.T t_id
的总和为
var groupObj = {};
list.forEach( ele =>
groupObj[ele.t_id] = groupObj[ele.t_id] ?
{title: ele.title, sum: groupObj[ele.t_id].sum + Number(ele.val1)} :
{title: ele.title, sum: Number(ele.val1) }
);
这将使groupObj
作为
{
1: { title: "cash to purchase", sum: 3 },
2: { title: "onroad", sum: 9 },
3: { title: "Onroad", sum: 11 }
}
如果您需要进一步的帮助,请添加注释。