$scope.arrSportData = data.sportdata;
angular.forEach($scope.arrSportData, function(value, key){
$scope.associatedSportplayer = value;
console.log($scope.associatedSportplayer);
//getting reponse
/*
Object { id: "1", user_id: "2", sport_id: "1", position_id: "1"}
Object { id: "2", user_id: "2", sport_id: "2", position_id: "6"}
Object { id: "3", user_id: "2", sport_id: "3", position_id: "12"}
Object { id: "4", user_id: "2", sport_id: "5", position_id: "20"}
*/
});
我想将sport_id选为数组,即数组[1,2,3,5]
请提前指导谢谢
答案 0 :(得分:2)
var datas = [{
id: "1",
user_id: "2",
sport_id: "1",
position_id: "1"
}, {
id: "2",
user_id: "2",
sport_id: "2",
position_id: "6"
}, {
id: "3",
user_id: "2",
sport_id: "3",
position_id: "12"
}, {
id: "4",
user_id: "2",
sport_id: "5",
position_id: "20"
}];
var sport_ids = datas.map(function(data) {
return Number(data.sport_id)
});
alert(sport_ids);

所以,你几乎可以利用javascript的map
函数来管理一种格式的数据,并将其转换为另一个数组,并从原始数组中提取数据。
答案 1 :(得分:0)
您可以在$scope
:
$scope.arrSportData = data.sportdata;
$scope.newArr = [];
angular.forEach($scope.arrSportData, function(value, key){
$scope.associatedSportplayer = value;
$scope.newArr.push($scope.associatedSportplayer.sport_id);
});
答案 2 :(得分:0)
这可能会帮助您将sport_id放入数组中。
var tempArr = [];
angular.forEach($scope.arrSportData, function(value, key){
tempArr.push(value.sport_id);
});
答案 3 :(得分:0)
试试这段代码。
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.arrSportData = [ { id: "1", user_id: "2", sport_id: "1", position_id: "1"},{ id: "2", user_id: "2", sport_id: "2", position_id: "6"},{ id: "3", user_id: "2", sport_id: "3", position_id: "12"},{ id: "4", user_id: "2", sport_id: "5", position_id: "20"}];
$scope.sportId = [];
angular.forEach($scope.arrSportData, function(value, key){
$scope.associatedSportplayer = value;
$scope.sportId.push($scope.associatedSportplayer.sport_id);
});
console.log($scope.sportId);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="plunker" ng-controller="MainCtrl">
</body>
答案 4 :(得分:0)
我不确切知道你需要它的位置,但这是一般的想法......
$scope.arrSportData = data.sportdata;
$scope.arrSportID = [];
angular.forEach($scope.arrSportData, function(value, key){
$scope.arrSportID.push(value.id);
}
console.log($scope.arrSportID);
答案 5 :(得分:-1)
您需要将值存储在对象中,然后将其推送到数组。
$scope.item = {};
$scope.addItem = function() {
var newItem ={};
newItem.name= $scope.item.name;
newItem.title=$scope.item.title;
$scope.contact.items.push(newItem);
console.log( $scope.contact.items);
}