我的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的总和..然后我想在我的HTML上
标题:购买现金
袋:3
名称:卸载
袋:9
标题:普通道路
袋:11
答案 0 :(得分:2)
你走了。端到端完整解决方案:
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>
答案 1 :(得分:1)
创建一个新对象以存储所有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 }
}
如果您需要进一步的帮助,请添加评论。