0

I have a JSON Array and i want to get the object which has the 'type':'optional'. how do i achieve that using forEach in Angular JS? please help me..

Please find below the JSON array

 $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"
  }
]
reptildarat
  • 1,036
  • 2
  • 18
  • 35
user3777846
  • 19
  • 1
  • 7
  • If you want to do the filtering in the view itself (ngRepeat) check out this example - http://stackoverflow.com/questions/14733136/angular-js-ng-repeat-filter-by-single-field – Faris Zacina Sep 22 '14 at 09:46

2 Answers2

1

It's fairly easy to do it

$scope.optional = []
angular.forEach($scope.headerAll, function (v) {
  if (v.type === 'optional') {
    $scope.optional.push(v)
  }
})
maurycy
  • 8,455
  • 1
  • 27
  • 44
0

it's bit faster and safer solution solution:

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

you can check performance here

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

plnkr

bmazurek
  • 169
  • 4
  • 1.1.5 in the comparision you provided is a bit outdated here is updated, check it out http://jsperf.com/angularjs-foreach-vs-native-foreach/23 – maurycy Sep 24 '14 at 10:36
  • and even better tests made by Igor Minar: http://jsperf.com/angularjs-foreach-vs-native-foreach/21 – maurycy Sep 24 '14 at 10:51