1

I am trying to break from a foreach loop. I want to test conditions and break from the loop once the condition is met. The problem is it keeps looping through the json array, even on the false ones. I just want it to stop if the condition is met. I am aware that you cannot actually break from a foreach loop but what is a good alternative here? I am having trouble understanding where to put the break statements. Thank you very much.

 $.ajax({
        // Get the values of the cce json file
        url: 'file.json',
        success: function (data) {
            data.forEach(function(row) {                  
              if (row.ATTR == feature.properties.AATR) {
                 // code to execute here
                 // once the condition is met once, stop execution of foreach
               } else {
                // some other code to execute
               // keep going
               }
blg2
  • 355
  • 6
  • 23
  • 3
    well forEach is the wrong loop if you want to break from it. You probably want to use every, some, or find depending on your goal. – epascarello Aug 23 '19 at 20:15

2 Answers2

1

You can't break forEach loop. You need to use a different type of loop.

See the docs:

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

Victor P
  • 1,496
  • 17
  • 29
0

You should use a for loop. It is a function that simulate it.

for (var i in data) {
    if (condition_to_break) {
        break;
    }
}

.forEach is a function and doesn't do break.