Skip to main content
2 of 2
added 476 characters in body
konijn
  • 33.8k
  • 5
  • 69
  • 264

Interesting question,

I think you wanted to check for vm.masterFormObject.payload.applicants not being undefined right before you do a forEach on it?

I would chain the undefined checks and use a falsey/truthy approach:

  if ( vm.masterFormObject && 
       vm.masterFormObject.payload && 
       vm.masterFormObject.payload.accounts) {
    //Do the thing
  }

Furthermore, since both accounts and applicants have data in .forms I would use a function to extract that.

Also, you have written your own version basically of Array.concat(), I would just use concat to keep it simple.

All in all that gives something like

vm.getAllForms = function (type) {

  var allForms = [],
      accountForms = [];
      applicantForms = [];

  function extractForms( records ){
    var forms = [];
    records.forEach(function (record) {
      if( record.Forms ){
        forms = forms.concat( record.Forms ); 
      }
    }
    return forms;
  }

  if ( vm.masterFormObject && 
       vm.masterFormObject.payload ){
    var payload = vm.masterFormObject.payload;
    if( payload.accounts ) {
      accountForms = extractForms( payload.accounts );
    }
    if( payload.applicants ) {
      applicantForms = extractForms(payload.applicants );
    }
  }
  allForms = accountForms.concat( applicantForms );

}

If this was a personal project I would have used this for extractForms:

  function extractForms( records ){
    var forms = [];
    records.forEach(function (record) {
        forms = forms.concat( record.Forms || [] ); 
    }
    return forms;
  }

It basically replaces record.Forms with an empty array if the value is undefined, it just looks more elegant to me, but probably would not pass most corporate code reviews.

konijn
  • 33.8k
  • 5
  • 69
  • 264