簡體   English   中英

將項目推入JSON數組

[英]Push an item into a JSON Array

我有一個JavaScript函數,它對API進行ajax調用,並獲得一個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,我都有一些“解釋”。 我想添加另一個屬性,以便有這樣的東西:

[
  {
    "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

每個錯誤都是一個對象,所以它沒有push,代碼應該是:

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

試試這種方式:

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM