devRena
devRena

Reputation: 327

how to push data into an array with key and value?

i have this object with arrays

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

i want to push into Variables {'VariableName': 'Total Active Energy'};

i did this

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

but in console I take :

0:{VariableName:'Total Active Energy'}
how can i push the value to take in console only {VariableName:'Total Active Energy'} without key 0 ?

i want this to have

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

Upvotes: 0

Views: 95

Answers (3)

Projesh Pal
Projesh Pal

Reputation: 458

You need to push object to the array

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>

Upvotes: 0

Pyae Phyoe Shein
Pyae Phyoe Shein

Reputation: 13847

it's not like that,

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

Upvotes: 1

Saeed
Saeed

Reputation: 5488

Look this code briefly

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)
 });

Upvotes: 0

Related Questions