R. Sharma
R. Sharma

Reputation: 49

Getting different value in array what I push

I am working on angular project. I am facing error that last value of object shown in all array.

$scope.products = [{"product_id":"1", "price:80"},{"product_id":"2", "price:90"}]

Now i am using angular forEach method. actually I have much thing I product array so i use a order array where I I provide just id and value

angular.forEach($scope.products, function(value, key){
   $scope.order.product_id = value.product_id;
   $scope.order.price = value.price;
   $scope.orderProducts.push($scope.order);

})

but I get

$scope.orders = [{"product_id":"2", "price:90"},{"product_id":"2", "price:90"}]

on my console I saw

objet{{"product_id":"1", "price:80"}

but when I open then I get

 product_id:"2",
 price: "90"

Upvotes: 2

Views: 68

Answers (3)

Swati
Swati

Reputation: 21

angular.foreach($scope.products, function(value, key){
   $scope.order.product_id = $scope.products.product_id;
   $scope.order.price = $scope.products.price;
   $scope.orderProducts.push($scope.order);

})

Firstly you should use the value inside the function to get the value of the product at that index .

angular.foreach($scope.products, function(value, key){
   $scope.order.product_id = value.product_id;
   $scope.order.price = value.price;
   $scope.orderProducts.push($scope.order);

})

Next you are changing the same object in the iteration i.e. $scope.order which means the first order pushed in the orderProducts array is changed when you assign the new values in the next iteration . You should make a local variable and then push it in the array .

angular.foreach($scope.products, function(value, key){
   val orderObj = {};
   orderObj.product_id = value.product_id;
   orderObj.price = value.price;
   $scope.orderProducts.push(orderObj);

})

Upvotes: 2

Rakesh Chand
Rakesh Chand

Reputation: 3113

Here is what you doing wrong

angular.foreach($scope.products, function(value, key){
   $scope.order.product_id = $scope.products.product_id;
   $scope.order.price = $scope.products.price;
   $scope.orderProducts.push($scope.order);
});

Repalce with

$scope.orderProducts = []
$scope.products = [{"product_id":"1", "price":80},{"product_id":"2", "price":90}]
angular.forEach($scope.products, function(value, key){
   $scope.orderProducts.push({
        product_id : value.product_id,
        price : value.price
   });
});

Upvotes: 0

shaunhusain
shaunhusain

Reputation: 19748

angular.foreach($scope.products, function(value, key){
   $scope.order.product_id = $scope.products.product_id;
   $scope.order.price = $scope.products.price;
   $scope.orderProducts.push($scope.order);

})

In the function you are using $scope.products instead of the value and key you are iterating over. Some other things aren't clear in your question so if you get that corrected and still have a problem maybe review the question to make sure you include enough detail (ideally running sample)

Upvotes: 1

Related Questions