我有一个json数据:
[{
"name": "a",
"data": "north",
"value": "10",
"finished": "50"
}, {
"name": "b",
"data": "north",
"value": "100",
"finished": "10"
}, {
"name": "c",
"data": "north",
"value": "20",
"finished": "50"
}, {
"name": "a",
"data": "south",
"value": "80",
"finished": "10"
}, {
"name": "b",
"data": "south",
"value": "100",
"finished": "10"
}, {
"name": "c",
"data": "south",
"value": "30",
"finished": "70"
}]
我想根据名称添加和分类数据。例如:" name" :""将有10 + 80 = 90,完成" 50 + 10" = 60,b的值为200,依旧等等。
我将json数据存储在角度范围内。
$scope.cuurentData = data;
var totalData = $scope.currentData;
for (var i = 0; i < totalData.length; i++) {
if (totalData.name === "a") {
// right code
}
}
请告诉我如何添加数据并在此处继续。
答案 0 :(得分:1)
$scope.currentData=data;
$scope.classifiedData=[];//This will hold the classified result
$scope.currentData.forEach(function(elem1){
var flag = false;
var i = 0;
$scope.classifiedData.forEach(function(elem2, index){
if(elem1.name == elem2.name){
flag = true;
i = index;
}
});
if(flag){
$scope.classifiedData[i].value = Number($scope.classifiedData[i].value)+Number(elem1.value);
$scope.classifiedData[i].finished = Number($scope.classifiedData[i].finished)+Number(elem1.finished);
}else{
$scope.classifiedData.push(elem1);
}
});
//Check the final result
console.log(JSON.stringify($scope.classifiedData));
答案 1 :(得分:0)
您可以使用javascript reduce功能
result = data.reduce(function(b, a){
var existing;
for (var i = 0; i < b.length; i++){
if(b[i].name == a.name) existing = b[i];
};
if (existing){
existing.value = Number(existing.value) + Number(a.value);
existing.finished = Number(existing.finished) + Number(a.finished);
} else {
b.push(a)
}
return b;
}, []);