Search code examples
vue.jsobjectvuejs2vue-componentv-for

Vue.js - How to display all property keys and nested property values?


Couldn't find a better title, my issue is hard to describe in one sentence. I'm trying to loop through an imported object generated by some third party package, but its structure is problematic:

obj: {
  "name1": {
    "property1": "value1",
    "property2": "value2",
  },
  "name2": {
    "property1": "value3",
    "property2": "value4",
  },
  "name3": {
    "property1": "value5",
    "property2": "value6",
  }
}

I want to display not just property1 and property2 but also the name preceding these:

- name1
  value1
  value2

- name2
  value3
  value4

...

This is the code I have so far:

<ul>
  <li v-for="(item, i) in obj" :key="index">
    {{ item.property1 }}
    <br>
    {{ item.property2 }}
  </li>
</ul>

How can I display the name as well, given this object' odd structure?

JSFiddle


Solution

  • Just add key property in your v-for loop and render it :

     <li v-for="(item,key, i) in obj" :key="index">
         {{key}}
          <br>
         {{ item.property1 }}
          <br>
          {{ item.property2 }}
      </li>