2014-09-03 136 views
3

我有這樣的:的Javascript改變特定對象屬性

$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,但我得到這個錯誤這一點,如果$scope.data

unexpected character found... 
+0

什麼是'data.content'? – dfsq 2014-09-03 10:54:07

+0

請發佈JSON,以便我們可以看一看。 – 2014-09-03 10:54:38

回答

1

我找到了一個解決方案:

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

說實話,我不知道爲什麼是這樣工作的,但它確實。 謝謝大家。

-1

使用使用具有對象的數組:

$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"; 
     } 

    } 
});