Home > Blockchain >  Looping through an object of arrays
Looping through an object of arrays

Time:03-22

I have an object, manageEmpForm that contains many manageEmployee arrays. I need to compare 2 different instances of this object and ensure every manageEmployee is equal. I'm having trouble wrapping my head around how to construct a loop to achieve the following functionality, without the specific index numbering:

const initialFormValues1 = this.manageEmpForm.controls.manageEmployees.value[0];
const initialFormValues2 = this.manageEmpForm.controls.manageEmployees.value[1];
...

const currentFormValues1 = this.manageEmpForm.controls.manageEmployees.value[0]; 
const currentFormValues2 = this.manageEmpForm.controls.manageEmployees.value[1]; 
...


formHasChanged = Object.keys(this.initialFormValues1).some(key => currentFormValues1[key] != this.initialFormValues1[key]) ||
      Object.keys(this.initialFormValues2).some(key => currentFormValues2[key] != this.initialFormValues2[key])

CodePudding user response:

You could use Array.some():

const formHasChanged = currentManageEmpForm.controls.manageEmployees.values.some((v, i) =>
  v != initialManageEmpForm.controls.manageEmployees.values[i]
)

Alternatively, you could use Array.every():

const formHasChanged = !currentManageEmpForm.controls.manageEmployees.values.every((v, i) =>
  v === initialManageEmpForm.controls.manageEmployees.values[i]
)

Note that both .some() and .every() accept a callback function with arguments: (element, index, array).

Working Example

const initialManageEmpForm = {
  controls: {
    manageEmployees: {
      values: [1, 2, 3]
    }
  }
}
const currentManageEmpForm = {
  controls: {
    manageEmployees: {
      values: [1, 2, 4]
    }
  }
}


const formHasChanged1 = currentManageEmpForm.controls.manageEmployees.values.some((v, i) =>
  v != initialManageEmpForm.controls.manageEmployees.values[i]
)

const formHasChanged2 = !currentManageEmpForm.controls.manageEmployees.values.every((v, i) =>
  v === initialManageEmpForm.controls.manageEmployees.values[i]
)


console.log(formHasChanged1);
console.log(formHasChanged2);

  • Related