0

I am looking for creating a menu by iterating on a nested object in the data object of Vuejs.

Here is the loop I have thought of:

<ul v-for="category in categories" :key="category">  {{ category }}
  <li v-for="subCategory in category" :key="subCategory">
    <router-link to="/"> {{ subCategory }} </router-link>
  </li>
</ul>

It would a simple menu with a one level of nested sub-menus.

categories: [{
  Atoms: ['Buttons', 'Icons'],
  Molecules: [],
  Organisms: [],
  Templates: [],
  Utilities: ['Grid']
}]

It is a component, so with the data: function(){}.

I know it is an easy problem but I don't manage to get a clean list with the menus (Atoms, Molecules...) as the ul, and the sub-menus (string in each array) as the li. Right now, I get the all array on the screen, with the [] and {}.

And I don't why Vuejs, when I look in Chrome console, adds some '0' objects between each layer of data.

Thanks for your help. I tried to make a JSfiddle but it didn't work at all.

1 Answer 1

1

What you can do is let categories be an object :

categories: {
  Atoms: ["Buttons", "Icons"],
  Molecules: [],
  Organisms: [],
  Templates: [],
  Utilities: ["Grid"]
}

And then use Object.entries(categories). This will transform the object into a 2 dimensional array where you can access both the name and the values while looping over it.

Object.entries

Vue.config.devtools = false;
Vue.config.productionTip = false;

var app = new Vue({
  el: '#app',
  data: {
    categories: {
      Atoms: ['Buttons', 'Icons'],
      Molecules: [],
      Organisms: [],
      Templates: [],
      Utilities: ['Grid']
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <ul v-for="[ category, subCategories ] in Object.entries(categories)" :key="category">
    {{category}}
    <li v-for="subCategory in subCategories" :key="subCategory">
      <div> {{ subCategory }} </div>
    </li>
  </ul>
</div>

[ category, subCategories ] in Object.entries(categories) here I am using array destructuring to directly decompose the object into to separate variable.

Sign up to request clarification or add additional context in comments.

2 Comments

It works, thanks. But is there any solution by just organizing correctly the data object?
Well you could organise categories like that : categories : [ { name : "Atoms", subCategories : ["Buttons", "Icons"] } ]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.