user6606700 user6606700 - 4 months ago 9
Javascript Question

How can I store data into array of AngularJS

$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

Answer

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.

Documentation