4

I am having an object like below.i will loop through the array of objects and check for any object property has "" value.the following code works very fine, it sets a flag to true,if any of the objects has an "" empty value,but it doesn't break out of the obj.forEach loop it just exists out of the immediate parent for loop only.how to exit out of the obj.forEach loop if any of the object property has "" value

var obj = [
  {
    "fname": "name1",
    "lname": ""
  },
  {
    "fname": "name2",
    "lname": "lname2"
  },
  {
    "fname": "",
    "lname": "lname3"
  }
];
var hasEmptyValue = false
var hasEmptyProperty = obj3.forEach(function(item) {
    for (var key in item) {
        if (item.hasOwnProperty(key) && item[key] == "") {
            saveIt = true;
            break;
        }
        console.log("key->",key,"value ->",item[key]); 
    }
});
yasarui
  • 6,209
  • 8
  • 41
  • 75
  • 3
    You don't, use `for` loop, if you need a breakable loop. – Teemu Jul 11 '17 at 07:40
  • So how i can achieve it without for loop – yasarui Jul 11 '17 at 07:41
  • 1
    Use `while` loop then. – Teemu Jul 11 '17 at 07:41
  • 2
    or simply use a `return`statement ... – Xatyrian Jul 11 '17 at 07:42
  • Ah maybe i didn't understand the question then : i thought he wanted to only stop for one item only – Xatyrian Jul 11 '17 at 07:44
  • @Xatyrian i tried return it doesn't work.my question is to exit out of the obj.Foreach loop when the object property is `""`. – yasarui Jul 11 '17 at 07:47
  • You mean stop iterating over the array or just stop for the current item ? – Xatyrian Jul 11 '17 at 07:48
  • @codegeek "So how i can achieve it without for loop" read linked question. There is more specific method for your requirements `obj3.some(item => Object.keys(item).some(key => item[key] == ''))` – Yury Tarabanko Jul 11 '17 at 07:48
  • @Xatyrian i have to stop iterating over the array not just the current item.the current solution is exit the loop for particular item – yasarui Jul 11 '17 at 07:51
  • @Yury Tarabanko can you elaborate little bit – yasarui Jul 11 '17 at 07:52
  • 2
    @codegeek `.forEach` is general iteration method that does something "for each" element in array. It has no notion of stop and is not the best option for your requirements. Since you want to check if **some** element has **some** value that is empty string there is godsend method just for you https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/some :) – Yury Tarabanko Jul 11 '17 at 07:56

1 Answers1

8

According to the MDN web docs:

There is no way to stop or break a forEach() loop other than by throwing an exception.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

maxpaj
  • 6,029
  • 5
  • 35
  • 56