使用forEach循环处理JSON

时间:2014-09-22 09:40:48

标签: angularjs

我有一个JSON数组,我希望得到具有'类型':'可选'的对象。我如何在Angular JS中使用forEach实现这一目标?请帮帮我..

请在下面找到JSON数组

 $scope.headerAll= 

 [
  {
    "field": "first_name",
    "displayName": "First name",
    "type": "required"
  },
  {
    "field": "last_name",
    "displayName": "Last Name",
    "type": "required"
  },
  {
    "field": "email",
    "displayName": "Email",
    "type": "required"
  },
  {
    "field": "isMarried",
    "displayName": "marital Status",
    "type": "optional"
  }
]

2 个答案:

答案 0 :(得分:1)

这很容易做到

$scope.optional = []
angular.forEach($scope.headerAll, function (v) {
  if (v.type === 'optional') {
    $scope.optional.push(v)
  }
})

答案 1 :(得分:0)

它更快更安全的解决方案解决方案:

 for (var i in $scope.headerAll){
    if ($scope.headerAll.hasOwnProperty(i) && $scope.headerAll[i].type === "optional"){
        console.log("do something");
    }
  }

你可以在这里检查表现

http://jsperf.com/angularjs-foreach-vs-native-foreach/5

plnkr