从json对象数组求和

时间:2017-02-22 07:42:28

标签: angularjs arrays json

android:maxLines="5"

我正在尝试总结" quecount"但未能得到结果

{ "Chemistry - II": [ { "id": "9", "title": "Solid State", "quecount": 12 }, { "id": "10", "title": "Solutions", "quecount": 9 }, { "id": "11", "title": "Electrochemistry", "quecount": 8 }, { "id": "6", "title": "d and f- Block elements", "quecount": 42 } ], "Physics": [ { "id": "3", "title": "Circular Motion", "quecount": 5 } ] }

帮助将受到高度赞赏。 谢谢..

4 个答案:

答案 0 :(得分:2)

您可以使用Array.prototype.map()Array.prototype.reduce()



let chlist = {
  "Chemistry - II": [{
    "id": "9",
    "title": "Solid State",
    "quecount": 12
  }, {
    "id": "10",
    "title": "Solutions",
    "quecount": 9
  }, {
    "id": "11",
    "title": "Electrochemistry",
    "quecount": 8
  }, {
    "id": "6",
    "title": "d and f- Block elements",
    "quecount": 42
  }],
  "Physics": [{
    "id": "3",
    "title": "Circular Motion",
    "quecount": 5
  }]
};

Object.values(chlist).forEach(function(v){
  console.log(v.map(o => o.quecount).reduce((a,b) => a + b));
});




答案 1 :(得分:0)

for (i = 0; i < $scope.chlist["Chemistry - II"].length; i++) {  
    total += $scope.chlist["Chemistry - II"][i].quecount;
} 

尝试添加键 - “化学 - II”

答案 2 :(得分:0)

var o = { "Chemistry - II": [ { "id": "9", "title": "Solid State", "quecount": 12 }, { "id": "10", "title": "Solutions", "quecount": 9 }, { "id": "11", "title": "Electrochemistry", "quecount": 8 }, { "id": "6", "title": "d and f- Block elements", "quecount": 42 } ], "Physics": [ { "id": "3", "title": "Circular Motion", "quecount": 5 } ] };

var total = 0;
for(var p in o) {
   if( Array.isArray(o[p]) ) {
      total = o[p].reduce((function(v, item) {
        return v + item.quecount;
      }, total);
   }   
}

答案 3 :(得分:0)

试试这个:

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl',function($scope) {
    
    $scope.jsonObj = {
	"Chemistry - II": [{
		"id": "9",
		"title": "Solid State",
		"quecount": 12
	}, {
		"id": "10",
		"title": "Solutions",
		"quecount": 9
	}, {
		"id": "11",
		"title": "Electrochemistry",
		"quecount": 8
	}, {
		"id": "6",
		"title": "d and f- Block elements",
		"quecount": 42
	}],
	"Physics": [{
		"id": "3",
		"title": "Circular Motion",
		"quecount": 5
	}]
};
    var chemistryQuecount = 0;
    var physicsQuecount = 0;
    for (var i in $scope.jsonObj) {
      if(i == 'Chemistry - II') {
        for(var j in $scope.jsonObj[i]) {
          chemistryQuecount += $scope.jsonObj[i][j].quecount;
        }
      }
      if(i == 'Physics') {
        for(var j in $scope.jsonObj[i]) {
          physicsQuecount += $scope.jsonObj[i][j].quecount;
        }
      }
    }
    console.log(chemistryQuecount);
    console.log(physicsQuecount);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
</div>