Looping through Object Properties
We previously saw how we can loop through an array of items. Something else we can do with the v-for directive is to loop through an object’s properties. First, I will show you how to loop through an object’s values.
The syntax for doing so is actually the same as with arrays. So all we need to do, is to give the current iteration’s value an alias. In this case, I will name the alias value.
<li v-for="value"></li>
Then we use the in keyword as we did before, followed by the name of the data property containing the object – in this case person.
<li v-for="value in person"></li>
We could also add a more complex expression such as a method invocation. The value alias will now contain the value of the object property for the current iteration of the loop, so now all we need to do is to output it with string interpolation.
<li v-for="value in person">
{{ value }}
</li>
If I run the code now, we should see the person object’s values being output in an unordered list. Now that was pretty easy, wasn’t it?
What we can also do, though, is to access the name of the property. To do this, we need to use the same syntax as in the previous post, where we accessed the loop index by adding parenthesis to the first part of the v-for directive. The first alias within the parenthesis is the value, so that part will remain the same. The second part is the object key, so I will name this propertyName.
<li v-for="(value, propertyName) in person">
With this, we can now output this value as well.
{{ propertyName }}: {{ value }}
This outputs a list with both the object keys and their corresponding values.
You might be wondering why the second alias is not the loop index as it was when using an array within the loop. The reason for this is that Vue.js distinguishes between the type of value that we are iterating through and populates the values for the aliases accordingly. So the semantics of the various alias positions are slightly different when iterating through an object’s keys.
But what if we also want to access the loop index when iterating through object keys? Fortunately, Vue.js got you covered. This index is available if you add a third alias within the parenthesis, so let’s do just that.
<li v-for="(value, propertyName, index) in person">
Let’s also output it in parenthesis after the object keys and values.
{{ propertyName }}: {{ value }} ({{ index }})
And there you have it! An object’s keys and values being output as well as the loop index.
Here is what you will learn:
- How to build advanced Vue.js applications (including SPA)
- How Vue.js works under the hood
- Communicating with services through HTTP
- Managing state of large applications with Vuex
- ... and much more!
One comment on »Looping through Object Properties«
Thanks for the short and compact video! :)