Madasu K
Madasu K

Reputation: 1863

need to collect each property values in an array of objects to separate arrays

I need to collect each property values in an array of objects int to separate property arrays, is there any simple way to do it. Either underscore and angularjs utilities are fine.

For example, I have an array of objects as,

 $scope.expNumArray = [];
 $scope.itemHrArray = []; 
 $scope.highReArray = [];

$scope.rowdata = [{
    "expNum": "678",    
    "itemHr": "",   
    "highRe": "C"
    }, {
    "expNum": "978",    
    "itemHr": "3",  
    "highRe": ""
}];

Now for this I need to have the following:

 $scope.expNumArray = ["678", "978"];

 $scope.itemHrArray = ["", "3"];

 $scope.highReArray = ["C",""];

Upvotes: 1

Views: 135

Answers (2)

Shushanth Pallegar
Shushanth Pallegar

Reputation: 2862

you can use angular's forEach to achieve this.

$scope.expNumArray = [];
 $scope.itemHrArray = []; 
 $scope.highReArray = [];



$scope.rowdata = [{
    "expNum": "678",    
    "itemHr": "",   
    "highRe": "C"
    }, {
    "expNum": "978",    
    "itemHr": "3",  
    "highRe": ""
}];

angular.forEach($scope.rowdata,function(value,key){

   $scope.expNumArray.push(value["expNum"]);
   $scope.itemHrArray.push(value["itemHr"]);
   $scope.highReArray.push(value["highRe"]);

});

Upvotes: 2

Jason Anderson
Jason Anderson

Reputation: 1

You can use underscore's each function to loop over

 $scope.rowdata

and append to each of the three other arrays. A bit cleaner than a Javascript for loop. This article about leveraging underscore might be of interest as well.

Upvotes: 0

Related Questions