2013-08-28 107 views
2

我有一個JavaScript函數,它可以調用API並調用JSON數組。將項目推送到JSON數組中

這裏是一個數組,我得到的一個樣本:

[ 
    { 
    "ErrorType": "Errors", 
    "Explanations": [ 
     { 
     "Explanation": "Price Missing", 
     "Locations": [ 
      25, 
      45 
     ] 
     }, 
     { 
     "Explanation": "Unit of measurement not valid", 
     "Locations": [ 
      25, 
      301, 
      302 
     ] 
     } 
    ] 
    }, 
    { 
    "ErrorType": "Warnings", 
    "Explanations": [ 
     { 
     Blablabla, 
     Ithinkthere's already much here 
     } 
    ] 
    } 
] 

我把它變成一個JavaScript數組:

$scope.CorrectionDatas = ResponseFromApi; 

所以,對於每一個錯誤類型,我有一些「解釋」。我想補充的另一個屬性,纔能有這樣的事情:

[ 
    { 
    "ErrorType": "Errors", 
    "Explanations": [ 
     { 
     "Explanation": "Price Missing", 
     "Locations": [ 
      25, 
      45 
     ] 
     }, 
     { 
     "Explanation": "Unit of measurement not valid", 
     "Locations": [ 
      25, 
      301, 
      302 
     ] 
     } 
    ], 
    "show": true 
    }, 
    { 
    "ErrorType": "Warnings", 
    "Explanations": [ 
     { 
     Blablabla, 
     Ithinkthere's already much here 
     } 
    ], 
    "show":true 
    } 
] 

不過,我覺得我能做到這一點只能通過做這樣的:

$scope.CorrectionDatas.forEach(function (error) { 
    error.push({ show: true }); 
}); 

但我的調試器給了我一個錯誤:

Error: error.push is not a function 
$scope.getErrors/</<@http://localhost:1771/dependencies/local/js/Correction/CorrectionCtrl.js:26 
+1

的問題是,雖然JSON響應構成的陣列,該陣列的每個元素是一個對象,而不是一個數組。 I.e'{「ErrorType」:「Warnings」,「Explanations」:[{Blablabla,我認爲這裏已經有很多了}}'是一個對象... – enhzflep

+1

你能顯示'typeof錯誤'的輸出嗎?我相信這是一個對象,而不是一個數組。 –

+0

正如我所說,我收到一個對象,thx爲你的幫助 –

回答

3

試試這個方法:

$scope.CorrectionDatas.forEach(function (error){ 
    error["show"] = true; 
}); 
4

每個錯誤是一個對象,因此它不具備推,代碼應該是:

 $scope.CorrectionDatas.forEach(function(error) { 
      error.show = true; 
     }); 
+0

工程一樣好我接受 –

3

我相信,您遇到的問題是,error不是一個數組,它是一個對象。這可以通過記錄typeof error的輸出來確認。如果是這樣的情況下,必須顯式地定義物體的show屬性,像這樣:

$scope.CorrectionDatas.forEach(function (error){ 
    error['show'] = true; // alternatively, error.show = true; 
}); 
相關問題