简体   繁体   中英

Dynamically loop on keys of object

I have an object coming from upload

obj: {
    name: 'Mike'
    street: 'Love'
}

and I can loop through it via

<div v-for="test in obj">
    <span>{{test.name}}, {{test.street}}</span>
</div>

and I get fine output.

However, the object keys became different depending on user upload, sometimes the key will become

obj: {
    address: 'street test 123',
    fine: '32 PHP',
    magic: 'Love'
}

How can I loop through it to become dynamic?

you have to take all keys in one array then you can bind it.

obj: {
address: 'street test 123',
fine: '32 PHP',
magic: 'Love'
}

var keys = Object.keys(obj);


<div>
    <span>{{keys.join(,)}}</span>
</div>

You can just loop through the whole object like this, here index is the variable name and item is the value

 var app4 = new Vue({ el: '#app-4', data: { obj: { address: 'street test 123', fine: '32 PHP', magic: 'Love' } } }) 
 <script src="https://unpkg.com/vue/dist/vue.js"></script> <div id="app-4"> <div v-for="(item, index) in obj"> <span>{{item}}</span> </div> </div> 

I don't think you want to use v-for for this purpose.

This is what I would do without changing how you have your obj set up:

<div id="foo">
  {{computedVal}}
</div>

and in the Vue instance,

new Vue({
   data: {
     // ... miscellaneous stuff
     obj: {
       prop1: 'val1',
       prop2: 'val2',
       prop3: 'val3',
     }
   },
   methods:{ /* ... */ },
   computed: {
      computedVal(){
        let str = '';
        for(let key in this.obj){
          let val = this.obj[key];
          str += `<span>${key} : ${val}</span>`;
        }
        return str;
      }
   }
});

This will be your output:

<div id="foo">
   <span>prop1 : val1</span>
   <span>prop2 : val2</span>
   <span>prop3 : val3</span>
</div>

Of course you can do this inside v-for as well.

My understanding is that as of now, Vue doesn't do object property iteration inside v-for .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM