Javascript 更改特定对象属性

标签 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...

最佳答案

我找到了一个解决方案:

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

相关文章:

javascript - 加载完所有内容后发出警报?

javascript - 如何在按钮单击事件上调用处理事件以添加新行的java脚本?

javascript - AngularJS 按键事件监听器 - 不是输入元素

javascript - 加载页面时多次获取请求

javascript - 从 1.2.x 更新后,指令不从 Controller ($scope)链接

javascript - 窗口缩小时动画图像从中心漂移

javascript - Angular 4 Universal this.html.charCodeAt 不是函数

javascript - 使用 ngClass 更改部分 CSS 类

javascript - 从 iPhone 上的全屏 Web 应用启动移动版 Safari

javascript - Angular : entering text into an input box, 将其保存在 ng-model 中