Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing key in Vue.js iteration

Tags:

vue.js

I have array like below

data() {
  return {
    shoppingItems: [
      {name: 'apple', price: '10'},
      {name: 'orange', price: '12'}
    ]
  }
}

I am trying to iterate like below

<ul>
  <li v-for="item in shoppingItems">
    {{ item.name }} - {{ item.price }}
  </li>
</ul>

I am getting output like below

  • apple - 10
  • orange - 12

But I would like to get output like below

  • name - apple, price - 10 //I would like to print key dynamically
  • name - orange, price - 12
like image 429
abu abu Avatar asked Jun 27 '18 06:06

abu abu


2 Answers

You can use (key,value) pair in for loop

var app = new Vue({
  el:'#app',
  data() {
  return {
    shoppingItems: [
      {name: 'apple', price: '10'},
      {name: 'orange', price: '12'}
    ]
  }
}
});
li span{
  text-transform: capitalize;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
<ul>
  <li v-for="item in shoppingItems">
    <span v-for="(v,i,count) in item">{{i}} - {{v}}<span v-show="count<(Object.keys(item).length-1)
">, </span></span>
  </li>
</ul>
</div>
like image 128
Niklesh Raut Avatar answered Sep 23 '22 05:09

Niklesh Raut


You can iterate over the keys/values with this :

<div v-for="(value, key) in object">
  {{ key }} - {{ value }}
</div>

You can also have the index of the current key :

<div v-for="(value, key, index) in object">
  {{ key }} - {{ value }}
  // if index > 0, add comma
</div>
like image 42
Thoomas Avatar answered Sep 25 '22 05:09

Thoomas