how to push a new array to json bracket angularJS

时间:2017-04-06 17:00:12

标签: javascript angularjs json push frontend

do you guys know how to push a to a json bracket if the json format like this ?

JSON FORMAT WHEN I PRINT

{  
   "19":[  
      {  
         "group_option_id":"19",
         "variant_id":"417000019",
         "option_value":"Blue",
         "variant_name":"M",
         "sku_code_per_item":"sk-blue-100",
         "prod_weight":"10",
         "prod_stock":"10"
      }
   ],
   "21":[  
      {  
         "group_option_id":"21",
         "variant_id":"417000024",
         "option_value":"Blue",
         "variant_name":"S",
         "sku_code_per_item":"sk-blue-100",
         "prod_weight":"100",
         "prod_stock":"100"
      }
   ]
}

Below is my angular file

        app.controller('edit_product_stock', function($scope,$http){



      $scope.product_id = function(prod_id) 
      {
        $scope.product_id = prod_id;
       $scope.get_stock = [];




         $http.get('get_variant_dtl_data?prod_id='+$scope.product_id+'').then(function(data) {
                console.log(data);
               $scope.get_stock = data.data;
            });

      };

     $scope.addNewChoice = function() 
      {

        $scope.get_stock.push({}); // what should i do to add new value in $scope.get_stock
      };

   });

Button to add new value html

  <button ng-click="addNewChoice()">Add new group variant</button>

i got this error when im execute / running the website using this script

$scope.get_stock.push is not a function

so that is my code so my plan is when im click the "add new group variant" button angular will be automatically create a new json value in $scope.get_stock

please help, thank you for your time

1 个答案:

答案 0 :(得分:0)

你无法将东西推入一个物体。您的JSON不是数组。 这将是一个数组:

[  
   {
       "19":[  
          {  
             "group_option_id":"19",
             "variant_id":"417000019",
             "option_value":"Blue",
             "variant_name":"M",
             "sku_code_per_item":"sk-blue-100",
             "prod_weight":"10",
             "prod_stock":"10"
          }
       ]
   },
   {
       "21":[  
          {  
             "group_option_id":"21",
             "variant_id":"417000024",
             "option_value":"Blue",
             "variant_name":"S",
             "sku_code_per_item":"sk-blue-100",
             "prod_weight":"100",
             "prod_stock":"100"
          }
       ]
   }
]