Reputation: 85
This function returns the same value in the array list.
For example if i=10
, then my array should contain 10 different values, but it stores only the last value 10 times.
What is the problem in my code?
$scope.webTempIds=[];
$scope.wId={};
$scope.getIds=function(){
for(var i=0;i<$rootScope.retData.length;i++){
$scope.wId.ID=$rootScope.retData[i].WEBUI_TEMP_ID;
$scope.webTempIds.push($scope.wId);
}
return $scope.webTempIds;
}
Upvotes: 3
Views: 100
Reputation: 2818
As others have correctly pointed out, you end up with the last item in the array because the value that you push to the array is on the $scope
and gets replaced with the new value each time.
To offer an alternative approach, you could use the Array.prototype.map function to return a new array prepopulated with just the id
property values of each data item:
$scope.getIds=function(){
$scope.webTempIds = $rootScope.retData.map(
function(obj){
return obj.id;
}
);
}
This eliminates the need for any loops with temporary variables and any push
ing to manually build up a new array from scratch.
Upvotes: 1
Reputation: 77904
This happens because you use $scope
for wId.ID
outside of loop. Therefore your list items point to the same object.
Once you change $scope.wId.ID
, the list $scope.webTempIds
will be updated too.
To fix it make id local:
for(var i=0;i<$rootScope.retData.length;i++){
var wId = {
ID: $rootScope.retData[i].WEBUI_TEMP_ID;
}
$scope.webTempIds.push(wId);
}
As a side note: use Scope to bind application controller and the view. (inside the for
loop you don't need scope)
Upvotes: 3
Reputation: 36
$scope.getIds=function(){
$scope.webTempIds=[];
for(var i=0;i<$rootScope.retData.length;i++){
$scope.wId={};
$scope.wId.ID =$rootScope.retData[i].WEBUI_TEMP_ID;
$scope.webTempIds.push($scope.wId);
}
return $scope.webTempIds;
}
Upvotes: 0
Reputation: 10458
$scope.wId={};
is changed every time. The array contains the reference to this object and hence when you change the value it changes the value in the array.
let obj = {};
let result = [];
for(let i = 0; i<10; i++){
obj.a = i;
result.push(obj);
}
console.log(result);
Upvotes: 3