Javascript更改特定对象属性

时间:2014-09-03 10:50:46

标签: javascript angularjs

我有这个:

$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...

2 个答案:

答案 0 :(得分:0)

我找到了解决方案:

$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!
    });

答案 1 :(得分:-2)

如果$scope.data包含对象数组,请使用此方法:

$http({
    method: "GET",
    url: myURL
}).
success(function (data, status) {
    $scope.data = data.content; //complex object
    for(var key in $scope.data){
        $scope.data[key].value1 = "newvalue1";
        $scope.data[key].value2= "newvalue2";
    }
});

或者value1和value2已经是$ scope.data的键,如

$scope.data = {
    value1: "me"
    value2: "you"
}

然后使用它:

$http({
    method: "GET",
    url: myURL
}).
success(function(data, status) {
    $scope.data = data.content; //complex object
    for (var key in $scope.data) {
        if (key == 'value1') {
            $scope.data[key]= "newvalue1";
        }

    }
});
相关问题