1

I have the following JSON array:

[
  { "id": "1", "service": "B" },
  { "id": "2", "service": "A" },
  { "id": "3", "service": "C" }
]

I want to check if the JSON array has service "A", if yes then return true.

I am using angular.js. I used angualr.forEach loop for it but break is not working in angular forEach. Is there any solution with JavaScript map function.

So, I want to create a function which has the above JSON array as an argument and returns true if the JSON array has a particular value("A") for a particular Key("service").

3 Answers 3

2

Use native JavaScript Array#some method.

var data = [{
  "id": "1",
  "service": "B"
}, {
  "id": "2",
  "service": "A"
}, {
  "id": "3",
  "service": "C"
}];

console.log(data.some(function(v) {
  return v.service == 'A';
}))


For older browser compatibility check polyfill option.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use angular foreach anyway. Set the flag to stop the loop. Try this.

var breakLoop = false;
angular.forEach(arr, function (val) {
   if (val.service == 'A') {
      breakLoop = true;
   }
});
console.log(breakLoop)

Comments

1

  function myFunction(data,myVal,myKey){
   var flag=false;
   angular.forEach(data,function(obj,k){
        if(obj[myKey]==myVal){
           flag=true;
          }
        });
   return flag;
  }

Comments

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.