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"
  }
]
1

2 Answers 2

1

It's fairly easy to do it

$scope.optional = []
angular.forEach($scope.headerAll, function (v) {
  if (v.type === 'optional') {
    $scope.optional.push(v)
  }
})
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

1.1.5 in the comparision you provided is a bit outdated here is updated, check it out jsperf.com/angularjs-foreach-vs-native-foreach/23
and even better tests made by Igor Minar: jsperf.com/angularjs-foreach-vs-native-foreach/21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.