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]; } } }); }
Using reduce() JavaScript's reduce() function iterates over the array like forEach() , but reduce() returns the last value your callback returns.
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.
Javascript: forEach : a return will not exit the calling function.
forEach executes the callback function once for each array element. It always returns undefined.
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]; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With