Lucien Chardon
Lucien Chardon

Reputation: 461

Iterate over object with count as value

In a Vue application, I have a data structure like this:

data: () => ({
    currentKey: 1,
    currentVal: 1,
    obj: {
      1: 3,
      2: 4,
      3: 2
    }
}),
methods: {
    stepForward() {
        // this method should update currentKey and currentVal 
    }
}

And a template with a simple button to iterate through the object.

<p>Key:{{ currentKey }} Value: {{ currentVal }}</p>
<v-btn @click="stepForward">Next</v-btn>

Problem

Clicking on the Next button, I would like to increase the values of currentKey and currentVal by iterating through the values of obj line by line.

Expected Result

With each click on the Next button the values would increase (until the last pair is reached) as follows:

currentKey: 1
currentVal: 1

currentKey: 1
currentVal: 2

currentKey: 1
currentVal: 3

currentKey: 2
currentVal: 1

currentKey: 2
currentVal: 2

currentKey: 2
currentVal: 3

currentKey: 2
currentVal: 4

currentKey: 3
currentVal: 1

currentKey: 3
currentVal: 2

How is it possible to achieve this?

Thanks for your help!

Upvotes: 0

Views: 83

Answers (2)

Tamerlan
Tamerlan

Reputation: 119

 if (this.currentVal === this.obj[this.currentKey]) {   
     this.currentKey += 1;
     this.currentVal = 1;
 } else {
     this.currentVal += 1;
 }

copy this code to your stepForward method

Upvotes: 0

Michael
Michael

Reputation: 591

I would recommend changing your object structure to be a bit more intuitive.

I'm not familiar with how vue tracks that incoming data object, but here's a rough idea:

if (currentVal === obj[currentKey]) {
  currentVal = 1;
  currentKey += 1;
} else {
  currentVal += 1;
}

Upvotes: 1

Related Questions