Reputation: 2164
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.
Upvotes: 1
Views: 4873
Reputation: 92324
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));
Upvotes: 3
Reputation: 2060
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.
Upvotes: 0
Reputation: 104795
Use .map
to loop the collection:
$scope.addresses = $scope.addresses.map(function(address) {
address.location = "X";
return address;
});
Upvotes: 1
Reputation: 2165
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';
Upvotes: 0