将项目推入JSON数组

时间:2013-08-28 12:41:43

标签: javascript arrays json angularjs

我有一个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

3 个答案:

答案 0 :(得分:4)

每个错误都是一个对象,所以没有推送,代码应该是:

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

答案 1 :(得分:3)

尝试这种方式:

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

答案 2 :(得分:3)

我相信您遇到的问题是error不是数组,而是一个对象。这可以通过记录typeof error的输出来确认。如果是这种情况,则必须明确定义对象的show属性,如下所示:

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