[Vuejs]-How do i acces the key and data of the array and show it?

1👍

Here’s a working example that uses a computed property to reformat the products array:

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

new Vue({
  el: '#app',
  data() {
    return {
      products: [{
        1337: {
          name: 'Product1'
        }
      }, {
        2222: {
          name: 'Product2'
        }
      }],
    };
  },
  computed: {
    simpleProducts() {
      return this.products.map(p => ({
        id: Object.keys(p)[0],
        name: Object.values(p)[0].name,
      }));
    },
  },
})
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>

<div id="app" class="container">
  <ul>
    <li v-for="product in simpleProducts" :key="product.id">
      <span>{{ product.id }}</span>
      <span>{{ product.name }}</span>
    </li>
  </ul>
</div>

Leave a comment