Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Angular forEach every item in a single array

Here i like to explain my problem clearly.

$http.get('arealist.json').success(function(response){
      angular.forEach(response, function(data){
           $scope.arealist = data.area_name;
           console.log($scope.arealist);
      });
});

Using the above code am getting area_name from arealist.json. and it looks like below image in console. console.log image

but i need the store above data in a array and it look like below

$scope.arealist = [ 
                    "Avadi", 
                    "Poonamallee",
                    "Padi", 
                    "Ambattur Industrial Estat",
                    "Annanagar",
                    "Arumbakkam",
                    "Kodambakkam",
                    "Nandanam"
                  ]

How can i do this ?

like image 789
Nodemon Avatar asked Jan 18 '16 07:01

Nodemon


People also ask

Can you use forEach on an array?

The forEach method is also used to loop through arrays, but it uses a function differently than the classic "for loop". The forEach method passes a callback function for each element of an array together with the following parameters: Current Value (required) - The value of the current array element.

How do you write a forEach loop in angular 6?

Syntax: arr. forEach(callback(currentValue[, index[, array]]) { // execute something }[, thisArg]);

What is forEach loop in angular?

forEach() Function in AngularJS is used to iterate through each item in an array or object. It works similar to the for loop and this loop contains all properties of an object in key-value pairs of an object. Syntax: angular.forEach(object, iterator, [context])

Does forEach () have a built in return value?

forEach executes the callback function once for each array element. It always returns undefined. It does not mutate the array, but the callback can if programmed to do so.


2 Answers

Declare a variable like below.

var arealistArray=[];
$scope.arealist=[]; 

Then push a value into array.

angular.forEach(response, function(data){
       arealistArray.push(data.area_name);
  });

Finally Assign the array to scope variable.

$scope.arealist=arealistArray;
like image 50
Thangadurai Avatar answered Sep 30 '22 15:09

Thangadurai


Use an array:

$scope.arealist = [];
$http.get('arealist.json').success(function(response){
      angular.forEach(response, function(data){
           $scope.arealist.push(data.area_name);
           console.log($scope.arealist);
      });
});
like image 41
Tarun Dugar Avatar answered Sep 30 '22 14:09

Tarun Dugar