[英]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. $scope.addresses
包含许多地址。
And lets say that each object has only have 4 properties; 假设每个对象只有4个属性。
$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. $scope.addresses[0].location
必须已经是一个对象,因为您正在为其设置属性。
To loop over addresses, use forEach or a standard for loop: 要循环遍历地址,请使用forEach或标准的for循环:
$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 或者您可以使用map替换整个地址对象
scope.addresses = addresses.map(address => Object.assign(
{location: 'X'}, address));
Use .map
to loop the collection: 使用.map
循环收集:
$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. 只需在执行赋值之前检查$ scope.addresses [0]是否存在,否则您将尝试访问“未定义”错误的属性。
so something like 所以像
if($scope.addresses[0])
$scope.addresses[0].location = 'Iceland';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.