简体   繁体   English

以计数为值遍历对象

[英]Iterate over object with count as value

In a Vue application, I have a data structure like this: 在Vue应用程序中,我具有如下数据结构:

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. 单击下一步按钮,我想通过currentKey迭代obj的值来增加currentKeycurrentVal的值。

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! 谢谢你的帮助!

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: 我不熟悉vue如何跟踪传入的数据对象,但是这里有一个大概的想法:

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

copy this code to your stepForward method 将此代码复制到stepForward方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM