如何将数据推入具有键和值的数组?

时间:2018-05-08 07:53:00

标签: javascript arrays angularjs object

我有这个带有数组的对象

$scope.filters = {     
      Sites: [], 
      Regions: [], 
      Devices : [], 
      Variables : [],      
     };

我想推进变量{'VariableName':'Total Active Energy'};

我做了这个

     var obj = {};
      obj['VariableName'] = response.data[0].AutoReportVariable;
      $scope.filters.Variables.push(obj);        
      console.log($scope.filters.Variables);

但在控制台中我采取:

  

0:{变量名称:'总活动能量'}
  如何在不使用键0的情况下将值推入控制台{VariableName:'Total Active Energy'}?

我想要这个

$scope.filters = {     
  Sites: [], 
  Regions: [], 
  Devices : [], 
  Variables : [{VariableName:'Total Active Energy'}]      
 };

3 个答案:

答案 0 :(得分:1)

它不是那样的,

$scope.filters = {     
    Sites: [], 
    Regions: [], 
    Devices : [], 
    Variables : [],      
};
$scope.filters.Variables.push({
    VariableName: 'Total Active Energy'
});
console.log($scope.filters.Variables);

答案 1 :(得分:0)

简要查看此代码



var $scope = {};

$scope.filters = {     
  Sites: [], 
  Regions: [], 
  Devices : [], 
  Variables : [{VariableName:'Total Active Energy'}]      
 };
 
 console.log("showing total araay:");
 console.log($scope.filters.Variables);
 
 console.log("showing item by item");
 $scope.filters.Variables.forEach(function(itm, index) {
  console.log("item " + JSON.stringify(itm) + " is in index " + index)
 });




答案 2 :(得分:0)

您需要将对象推送到数组



angular.module('myApp', []).controller('namesCtrl', function($scope) {
  $scope.filters = {     
    Sites: [], 
    Regions: [], 
    Devices : [], 
    Variables : []      
   };
   for(var i=0;i<10;i++){
   
   var obj={VariableName:'Total Active Energy'+i};
   $scope.filters.Variables.push(obj);
   }
   angular.forEach($scope.filters.Variables, function(value, key) {
   console.log("item " + JSON.stringify(value) + " is in index " + key)
   });
   
   
});
&#13;
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="namesCtrl">
  <ul>
      <li ng-repeat="x in filters.Variables">
        VariableName: {{x.VariableName}}
      </li>
  </ul>

</div>

</body>
</html>
&#13;
&#13;
&#13;