In Vue.js, we can use v-for to render an Array as an HTML table or list nicely. But if we want to render an Object’s keys and values as a table, for example, I use JS Objects and an Array to store a lot of contact info, and each contact has different keys. I want to display the info for Contact 1 in a table. It seems v-for isn’t a good fit here?
For example, I want to convert a JS Object to HTML like below:
{
"name": "Karl",
"age": 10,
"school": "NTUST"
}HTML:
<p>name:Karl</p> <p>age:10l</p> <p>school:NTUST </p>
At first, I tried using Object.keys and v-for to solve this, but I think it’s very messy. Then I found a nice syntax that solves it:
<p v-for="(val, key) in contacts[0]">{{key}}:{{val}}</p>