0

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?

3
  • you would not need a for loop if each button press creates a single item - just create function addFeatureObj = () => featureObjArray.value.push({ id: null, feature: null }); ... and call it on click ... Commented Jun 17, 2022 at 3:57
  • Ah ok. If I use featureObjArray.value.push({ id: null, feature: null }) instead, how can I prevent the user from adding more than 5 objects to the array? Commented Jun 17, 2022 at 4:00
  • before pushing, test length Commented Jun 17, 2022 at 4:01

1 Answer 1

2

Just check the length of the array before pushing:

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.