shady87 shady87 - 5 months ago 8
AngularJS Question

Add properties to array objects - AngularJS

How can I add properties to objects in an array by looping through the array?

Example I have an array with objects;

$scope.addresses
contains many addresses.

And lets say that each object has only have 4 properties;

$scope.addresses[0].address_line1
$scope.addresses[0].address_line2
$scope.addresses[0].address_line3
$scope.addresses[0].city


Now I want to add more properties to each of the objects in the array.

$scope.addresses[0].location
$scope.addresses[0].neighbourhood


Any help appreciated.

Answer

Use .map to loop the collection:

$scope.addresses = $scope.addresses.map(function(address) {
      address.location = "X";   
      return address;
});
Comments