Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grab the return value and get out of forEach in JavaScript? [duplicate]

Tags:

How can I modify this code so that I can grab the field.DependencyFieldEvaluated value and get out of the function as soon 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];                              }                         }                     });                 } 
like image 304
Maryam Avatar asked Feb 17 '16 06:02

Maryam


People also ask

How do I get a refund from forEach?

Using reduce() JavaScript's reduce() function iterates over the array like forEach() , but reduce() returns the last value your callback returns.

How do you break out of a forEach?

To break a forEach() loop in TypeScript, throw and catch an error by wrapping the call to the forEach() method in a try/catch block. When the error is thrown, the forEach() method will stop iterating over the collection.

Does return exit forEach JavaScript?

Javascript: forEach : a return will not exit the calling function.

Can we return value in forEach?

forEach executes the callback function once for each array element. It always returns undefined.


1 Answers

Use a good old vanilla for 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 stay fancy, use filter again:

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]; } 
like image 113
lxe Avatar answered Oct 12 '22 13:10

lxe