Take the return value and exit forEach in JavaScript?

How can I change this code so that I can capture the field. Independent value FieldEvaluated and exit the function as soon as I get this value?

function discoverDependentFields(fields) {
                    fields.forEach(function (field) {
                        if (field.DependencyField) {
                            var foundFields = fields.filter(function (fieldToFind) { return fieldToFind.Name === field.DependencyField; });
                            if (foundFields.length === 1) {
                               return field.DependencyFieldEvaluated = foundFields[0];

                            }
                        }
                    });
                }
+4
source share
3 answers

Use good old vanilla for a loop:

function discoverDependentFields(fields) {
  for (var fieldIndex = 0; fieldIndex < fields.length; fieldIndex ++) {
    var field = fields[fieldIndex];

    if (field.DependencyField) {
      var foundFields = fields.filter(function(fieldToFind) {
        return fieldToFind.Name === field.DependencyField;
      });
      if (foundFields.length === 1) {
        return foundFields[0];
      }
    }
  }
}

Well, if you want to remain a fantasy, use filter:

function discoverDependentFields(fields) {
  return fields.filter(function(field) {
    if (field.DependencyField) {
      var foundFields = fields.filter(function(fieldToFind) {
        return fieldToFind.Name === field.DependencyField;
      });
      if (foundFields.length === 1) {
        return foundFields[0];
      }
    }
  })[0];
}
+4
source

instead of fields. You can use fields.map for this. here is an example:

var source=[1,2,3,4,5];

var destination=source.map(function(item){
 if(item==3)
     return 'OUTPUT';
}).filter(function(item){return item;})[0];

console.log(destination); // prints 'OUTPUT'
Run codeHide result
+1
source

return, , .

[1, 2, 3, 4, 5, 6].forEach(function(value){
  if(value > 2) return; 
  console.log(value)
});
0

Source: https://habr.com/ru/post/1629105/


All Articles