简体   繁体   中英

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.

Just assign a new property

$scope.addresses[0].location = 'Roxbury'

$scope.addresses[0].location must already be an object since you are setting properties on it.

To loop over addresses, use forEach or a standard for loop:

$scope.addresses.forEach(function(address, index) {
    address.location = locations[index];
});

for(var i=0; i < $scope.addresses.length; i++) {
  $scope.addresses[i].location = myLocations[i];
}

Or you could replace the entire addresses object using map

scope.addresses = addresses.map(address => Object.assign(
    {location: 'X'}, address));

Use .map to loop the collection:

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

Simply using the . dot notion should do.

$scope.addresses[0].location = 'Iceland';

Just check for existence of $scope.addresses[0] before you do the assignment though otherwise you will get trying to access property of 'undefined' errors.

so something like

if($scope.addresses[0])
    $scope.addresses[0].location = 'Iceland';

You can use forEach loop and then add required items inside it:

angular.forEach($scope.addresses, function(v, k) {
    v.location = "New location " + (k + 1);
    v.neighbourhood = "New neighbourhood " + (k + 1);
  });

Watch demo here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM