简体   繁体   中英

Push an item into a JSON Array

I have a JavaScript function that makes an ajax call to an API, and gets a JSON array.

Here is a sample of an array that I get:

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

I put it into a JavaScript array:

$scope.CorrectionDatas = ResponseFromApi;

So, for each ErrorType, I have some "explanations". I would like to add another property, in order to have something like this :

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

I though that I could do it only by doing it like that:

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

But my debugger gives me an error:

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

Each error is an object so it don't have push, the code should be:

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

Try this way:

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

I believe that the problem you're encountering is that error is not an array, it is an object. This can be confirmed by logging the output of typeof error . If this is the case, you must explicitly define the show property of the object, as so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM