我有这个:
$http({
method: "GET",
url: myURL
}).
success(function (data, status) {
$scope.data = data.content; //complex object
for(i=0;i<$scope.data.length;i++){
$scope.data[i].value1 = "newvalue1";
$scope.data[i].value2= "newvalue2";
}
});
如何更改对象数组中某个点的属性?
我收到这个错误,即使我知道它存在
$scope.data[i] is undefined
我尝试解析 JSON,但出现此错误
unexpected character found...
最佳答案
我找到了一个解决方案:
$http({
method: "GET",
url: myURL
}).
success(function (data, status) {
$scope.data = data.content; //complex object
for(i=0;i<$scope.data.length;i++){
var x = $scope.data[i];
x.value1 = "newvalue1";
x.value2= "newvalue2";
$scope.data[i].value1 = x.value1;
$scope.data[i].value2 = x.value2;
}
});
老实说,我不知道为什么会这样,但确实如此。 谢谢大家。
编辑 04/2018
我正在查看我的旧问题......使用 AngularJS 的更好方法如下:
$http({
method: "GET",
url: myURL
}).
then(function (response) {
/**
* Remember to use clear identifiers
* to always see what is in a variable
* without having to investigate each time
*/
$scope.myObjectList = response.content;
/**
* If I remember correctly,
* response.content was an array of objects,
* used to print some page in the view (ng-repeat)
*/
var i = -1
while(++i<$scope.myObjectList.length){
angular.extend($scope.myObjectList[i], {
value1: "newvalue1",
value2: "newvalue2"
});
}
/**
* angular.forEach would also be an option,
* or _.each if you have lodash
*/
}, function(error){
//Don't forget to handle errors!
});
关于Javascript 更改特定对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25642432/