js數組裡物件的某一列相加
阿新 • • 發佈:2019-01-26
js 物件陣列,裡面的某一項值相加,比如下例中,當a的值相同時,num列相加,之後得到最終陣列
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1" >
</head>
<body>
<script>
var newfood=[]
var arry=[
{'a':'1a','num':1},
{'a':'1a','num':1},
{'a':'2a','num':1},
{'a':'3a','num':2},
{'a':'1a','num':8},
]
var temp = {};
for(var i in arry) {
var key= arry[i].a;
if (temp[key]) {
temp[key].a = temp[key].a ;
temp[key].num = temp[key].num+ arry[i].num;
} else {
temp[key] = {};
temp[key].a = arry[i].a;
temp[key].num = arry[i].num;
}
}
console.log(temp);
for (var k in temp){
newfood.push(temp[k])
}
console.log(newfood);
</script>
</body>
</html>