js数组里对象的某一列相加

js 对象数组,里面的某一项值相加,比如下例中,当a的值相同时,num列相加,之后得到最终数组


<html>
<head>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Page Titletitle>
  <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>

js数组里对象的某一列相加_第1张图片

你可能感兴趣的:(js)