How do you use v-for to render a list showing city names and their users' names inside each city?
hard
A. <div v-for="(users, city) in usersByCity" :key="city">
<h3>{{ city }}</h3>
<ul>
<li v-for="user in users" :key="user.id">{{ user.name }}</li>
</ul>
</div>
B. <div v-for="city in usersByCity" :key="city">
<h3>{{ city }}</h3>
<ul>
<li v-for="user in city" :key="user.id">{{ user.name }}</li>
</ul>
</div>
C. <div v-for="(city, users) in usersByCity" :key="city">
<h3>{{ city }}</h3>
<ul>
<li v-for="user in users" :key="user.id">{{ user.name }}</li>
</ul>
</div>
D. <div v-for="user in usersByCity" :key="user.id">
<h3>{{ user.city }}</h3>
<ul>
<li>{{ user.name }}</li>
</ul>
</div>
Solution
Step 1: Understand the data structure
usersByCity is an object where keys are city names and values are arrays of user objects.
Step 2: Use v-for to loop over object entries
Use v-for="(users, city) in usersByCity" to get city name and users array. Then loop over users array inside.
Step 3: Check options for correct variable order and keys
<div v-for="(users, city) in usersByCity" :key="city">
<h3>{{ city }}</h3>
<ul>
<li v-for="user in users" :key="user.id">{{ user.name }}</li>
</ul>
</div> correctly uses (users, city) and nested v-for with keys. <div v-for="(city, users) in usersByCity" :key="city">
<h3>{{ city }}</h3>
<ul>
<li v-for="user in users" :key="user.id">{{ user.name }}</li>
</ul>
</div> swaps city and users order incorrectly. Options B and D misuse variables.
Final Answer:
Option A code snippet correctly renders cities and their users. -> Option A
Quick Check:
Object loop: (value, key) = (users, city) [OK]
Hint: For objects, v-for uses (value, key) in object [OK]
Common Mistakes:
Swapping key and value order in v-for
Using array syntax for object iteration
Missing unique :key on nested loops
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.