如何使用forEach函数

时间:2016-04-13 06:45:00

标签: javascript jquery angularjs

我在显示来自JSON文件的数据方面遇到了一些麻烦:

目前"checked": null。我想使用checked = true循环在步骤数组中执行forEach

这是我的JSON数据:

{
  "id": 4,
  "process": {
    "id": 24,
    "name": "test-1Process",
    "description": "Unknown",
    "steps": [
      {
        "id": 6,
        "title": "test1-process",
        "description": "test1 FDescriptin",
        "assetURL": "",
        "checked": null
      },
      {
        "id": 7,
        "title": "test1-step2",
        "description": "step2 description",
        "assetURL": "",
        "checked": null
      }
    ],
    "possibleEndStates": [
      {
        "id": 1,
        "name": "test2-tesp2"
      },
      {
        "id": 1,
        "name": "test2-tesp2"
      }
    ]
  },
  "user": {
    "id": 5,
    "firstname": "john",
    "surname": "edd",
    "email": "john@gmail.com ",
    "companyAdministrator ": false,
    "roles ": [
      {
        "id ": 2,
        "name ": "test1 - role ",
        "department ": {
          "id ": 2,
          "name ": "test1 - department ",
          "description": null,
          "company": {
            "id": 2,
            "name": "sd",
            "address": "default",
            "timezoneId": "default",
            "logoURL": "default"
          }
        }
      }
    ]
  }
}

然后推入steps变量步骤数组。 请给我一些建议。

3 个答案:

答案 0 :(得分:2)

  

目前"已检查":null我想在步骤数组中检查= true   使用foreach循环

data.process.steps.forEach(function(val){
  val.checked = true;
});

答案 1 :(得分:1)

试试这个 -

function changeKeyVal(element, index, array) {
   array[index]["checked"] = 'Value Renewed '+index;
  console.log(array[index]["checked"]);
}
data.process.steps.forEach(changeKeyVal);

答案 2 :(得分:0)

您也可以使用Angular的内置迭代器,因为您使用的是Angular:

angular.forEach(data.process.steps, function(step) {
    step.checked = true;
});