Search code examples
javascripthtmljsonvue.jslistview

How to display an Object containing other Objects in Vue.js


I'm new at using Vue.js and I was wondering how to display this JSON object:

{
    "1": [
        "15-16",
        "16-17",
        "17-18",
        "18-19"
    ],
    "2": [
        "15-16",
        "16-17",
        "17-18",
        "18-19"
    ]
}

in a list that has this structure:

<div>
<h1>The key of the object...</h1>
  <ul>
    <li>The list of all the strings inside the array</li>
  </ul>
</div>

Solution

  • loop object and then loop the array inside, here is a working example

    https://codesandbox.io/s/eager-leaf-nx2mq?file=/src/App.vue

    <template>
      <div id="app">
        <div v-for="(value, propertyName) in data" :key="propertyName">
          <h1>The key of the {{ propertyName }}</h1>
          <ul>
            <li v-for="(item, index) in data[propertyName]" :key="index">
              {{ item }}
            </li>
          </ul>
        </div>
      </div>
    </template>
    
    <script>
    export default {
      name: "App",
      components: {},
      data() {
        return {
          data: {
            1: ["15-16", "16-17", "17-18", "18-19"],
            2: ["15-16", "16-17", "17-18", "18-19"],
          },
        };
      },
    };
    </script>