Home > Mobile >  How to push objects to an array in Vue 3 while i < 5
How to push objects to an array in Vue 3 while i < 5

Time:06-17

I am attempting to set up a button function in Vue 3 that handles pushing objects to an array in a for loop, while i < 5:

const addFeatureObjs = () => {
  for (let i = 0; i < 5; i  ) {
    // featureObjArray.value.push({ id: null, feature: null })
    featureObjArray.value[i] = { id: null, feature: null }
  }
}

So far, I have a for loop set up to create 5 instances of the object while i < 5. However, I wish to set up this function so that each button click call to addFeatureObjs creates a new object one click at a time until 5 are created, instead of calling addFeatureObjs to create the 5 objects all at once. How can I go about setting up this function, for loop, and array to enable creating each object one at a time, until 5 are created?

CodePudding user response:

Just check the length of the array before pushing:

const addFeatureObjs = () => {
  if (featureObjArray.value.length <= 5) {
    featureObjArray.value.push({ id: null, feature: null });
  }
}

  • Related