【问题标题】:Push an item into a JSON Array将项目推送到 JSON 数组中
【发布时间】:2013-08-28 12:41:42
【问题描述】:

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

【问题讨论】:

  • 问题在于,虽然 JSON 响应构成一个数组,但该数组的每个元素都是一个对象,而不是一个数组。即{"ErrorType":"Warnings", "Explanations":[{ Blablabla, I think there's already much here }]} 是一个对象...
  • 你能显示'typeof error'的输出吗?我相信这是一个对象,而不是一个数组。
  • 据说,我收到了一个对象,谢谢你的帮助

标签: javascript arrays json angularjs


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    试试这个方法:

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-10
        • 2020-04-22
        • 2015-09-13
        • 1970-01-01
        • 2015-03-31
        • 1970-01-01
        相关资源
        最近更新 更多