我有一个返回对象数组data.sportdata
的函数。我想让所有数组元素具有相同的sports_id。代码
$scope.arrSportData = data.sportdata;
angular.forEach($scope.arrSportData, function(value, key) {
console.log($scope.arrSportData);
//getting reponse
/*
Object { id: "1", user_id: "2", sport_id: "1", position_id: "1", team_name: "JimmyTmname",}
Object { id: "2", user_id: "2", sport_id: "2", position_id: "6", team_name: "JimmyTmname2",}
Object { id: "3", user_id: "2", sport_id: "3", position_id: "12", team_name: "JimmyTmname3",}
Object { id: "4", user_id: "2", sport_id: "5", position_id: "20", team_name: "JimmyTmname5",}
*/
//code i wrote
if (value.sport_id == 1) {
$scope.positionId.spr1 = value.position_id;
$scope.teamname.spr1 = value.team_name;
}
if (value.sport_id == 2) {
$scope.positionId.spr2 = value.position_id;
$scope.teamname.spr2 = value.team_name;
}
if (value.sport_id == 3) {
$scope.positionId.spr3 = value.position_id;
$scope.teamname.spr3 = value.team_name;
}
if (value.sport_id == 4) {
$scope.positionId.spr4 = value.position_id;
$scope.teamname.spr4 = value.team_name;
}
});
在这里,我总是获得第一价值,仅此而已。请建议并帮助解决这个问题。
我确实在循环之外尝试但是不起作用。我认为过滤功能可以做到这一点,但不知道它是如何工作的。
答案 0 :(得分:0)
执行groupBy函数,它将为您提供类似这样的对象
{
key: [],
key: []
}
此处的密钥为sport_id,[]
将为具有相同密钥的项目。
最小的工作示例是,
// Written By: Ceaser Bautista
//Link: http://stackoverflow.com/a/34890276/17447
var groupBy = function(xs, key) {
return xs.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
//here we have four teams with two sports id 13 and 22
var arrSportData = [{
id: "1",
user_id: "1",
sport_id: "13",
position_id: "1",
team_name: "JimmyTmname"
}, {
id: "2",
user_id: "2",
sport_id: "22",
position_id: "6",
team_name: "JimmyTmname2"
}, {
id: "3",
user_id: "3",
sport_id: "22",
position_id: "12",
team_name: "JimmyTmname2",
}, {
id: "4",
user_id: "4",
sport_id: "13",
position_id: "20",
team_name: "JimmyTmname1"
}];
$scope.groupedData = groupBy(arrSportData, "sport_id");
console.log(groupedData);
现在,每个sports_id都有一个数组。在视图中填充它像
<div ng-repeat="(key, items) in groupedData">
<h4>Sports ID: {{key}}</h4>
<ul ng-repeat="item in items">
<li>User ID: {{item.user_id}}</li>
</ul>
</div>