1

How do we loop over a variable of type Record<string, string[]> in Vue? My variable contains a key-value dictionary that looks like this:

errors = {
  'username': ['Must contain at least 1 special character', 'Min length is 6'],
  'password': ['Required']
}

I tried this but Vue (or TS or ESLint, not sure) is not happy:

<ul>
  <li v-for="e in errors" :key="e">
    {{ e }}
    <ul>
      <li v-for="e2 in e" :key="e2">
        {{ e2 }}
      </li>
    </ul>
  </li>
</ul>

It shows this error for the first :key above:

`Type 'string[]' is not assignable to type 'string | number | symbol | undefined'

BTW, I'm using Vue 3 with TS. errors is part of an interface and is defined as Record<string, string[]>.

dotNET
  • 33,414
  • 24
  • 162
  • 251
  • In the second loop, it's an array, so it should be `e2 of e`. – kelsny Oct 08 '22 at 13:05
  • @caTS: Is there a difference between the usage of `of` and `in` in Vue? – dotNET Oct 08 '22 at 13:21
  • Vue uses JS' loops, so you can find the difference between them [here](https://stackoverflow.com/questions/29285897/what-is-the-difference-between-for-in-and-for-of-statements). – kelsny Oct 08 '22 at 13:21

1 Answers1

0

Found it. The outer loop needs to declare its variable as array like this:

<ul>
  <li v-for="[cat, errs] in msg.errors" :key="cat">
    {{ cat }}
    <ul>
      <li v-for="e2 of errs" :key="e2">
        {{ e2 }}
      </li>
    </ul>
  </li>
</ul>
dotNET
  • 33,414
  • 24
  • 162
  • 251