как вставить данные в массив с ключом и значением? - PullRequest
0 голосов
/ 08 мая 2018

у меня есть этот объект с массивами

$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: {VariableName: 'Общая активная энергия'}
Как я могу нажать значение, чтобы принять только в консоли {VariableName: 'Total Active Energy'} без ключа 0?

я хочу, чтобы это было

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

Ответы [ 3 ]

0 голосов
/ 08 мая 2018

это не так,

$scope.filters = {     
    Sites: [], 
    Regions: [], 
    Devices : [], 
    Variables : [],      
};
$scope.filters.Variables.push({
    VariableName: 'Total Active Energy'
});
console.log($scope.filters.Variables);
0 голосов
/ 08 мая 2018

Вам нужно поместить объект в массив

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)
   });
   
   
});
<!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>
0 голосов
/ 08 мая 2018

Кратко посмотрите этот код

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)
 });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...