2

I'm new to vuejs. I started to play with v2. I have a simple array with object in my instance data property:

items: [{"theProprtyName": "thePropertyValue"}]

I do simple v-for:

<v-list>
    <v-list-item v-for="item in items">
        <span v-for="(key, value) in map">
            {{key}}--{{value}}
        </span>
    </v-list-item>
</v-list>

renders:

theProprtyName--thePropertyValue

Is there a more elegant way to create to achieve the end result?

Thanks in advance

3
  • what is mappings? Commented Jan 29, 2017 at 9:52
  • You can create a function that accepts the items array and returns an object that has known properties like 'key' and 'value' an then in the v-for access them as 'item.key' and 'item.value'. Commented Jan 30, 2017 at 14:37
  • nice and simple but not vue-ish. not sure which one I prefer, thanks Commented Jan 30, 2017 at 14:50

2 Answers 2

8

You can get the property name referencing the name, instead of the index, in the v-for:

<div v-for="(item, name) in items" :key="name"> {{name}}</div>
Sign up to request clarification or add additional context in comments.

Comments

1

I think the most straightforward solution is to make use of computed properties:

const app = new Vue({
  el: '#app',
  data: {
    list: [
      {
        foo: 'value1',
        bar: 'value2',
        baz: 'value3'
      },
      {
        foo: 'value4',
        bar: 'value5',
        baz: 'value6'
      }
    ]
  },
  computed: {
    objList() {
      return this.list.map((item) => Object.keys(item))
    },
    keyValuePair() {
      return this.list.map((item) => {
        return Object.keys(item).reduce((acc, curr) => {
          acc.push(`${curr} - ${item[curr]}`)
          return acc
        }, [])
      })
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
<div id="app">
  <div>
    <h3>Loop as normal</h3>
    <div v-for="item in list">{{item}}</div>
  <div>
  <div>
    <h3>Loop as normal</h3>
    <div v-for="item in objList">{{item}}</div>
  <div>
  <div>
    <h3>Key-Value Pair</h3>
    <div v-for="(item, idx) in keyValuePair">
      <div>{{item}}</div>
    </div>
  <div>
</div>

Comments

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.