Reputation: 811
$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"}
*/
});
I would like to pick the sport_id into array i.e array [1,2,3,5]
Please guide thanks in advance
Upvotes: 2
Views: 7035
Reputation: 148
You need to store the values in an object and then push it to array.
$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);
}
Upvotes: -1
Reputation: 1794
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);
So, you can pretty much make use of javascript's map
function to pipe an array of data in one format and convert it into another array with extracted data from original array.
Upvotes: 2
Reputation: 67
I don't know exactly where you need it, but this is the general idea...
$scope.arrSportData = data.sportdata;
$scope.arrSportID = [];
angular.forEach($scope.arrSportData, function(value, key){
$scope.arrSportID.push(value.id);
}
console.log($scope.arrSportID);
Upvotes: 0
Reputation: 3350
Try this code.
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>
Upvotes: 0
Reputation: 6628
This might help you to have sport_id into an array.
var tempArr = [];
angular.forEach($scope.arrSportData, function(value, key){
tempArr.push(value.sport_id);
});
Upvotes: 0
Reputation: 74738
You can push to a empty array at the $scope
:
$scope.arrSportData = data.sportdata;
$scope.newArr = [];
angular.forEach($scope.arrSportData, function(value, key){
$scope.associatedSportplayer = value;
$scope.newArr.push($scope.associatedSportplayer.sport_id);
});
Upvotes: 0