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.
4 Answers 4
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));
3 Comments
$scope.addresses how will I do it? I can't do it manually by adding [0], [1] etc... So I would need to loop and add to allangular I'm a PHP developerUse .map to loop the collection:
$scope.addresses = $scope.addresses.map(function(address) {
address.location = "X";
return address;
});
3 Comments
forEach and drop the return...addresses.map(address => Object.assign({location: 'X'}, address))forEach, or you should be returning modified objects in the map function. Sorry, but I really dislike the misuse of Array#map "use map to loop over a collection" is really bad advice, "use map to create a new array with modified items" is much more true to map's semanticsSimply 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';
Comments
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.
Array.prototype.map()trueorfalse