Reputation: 2945
I'm having trouble iterating over data from a json file in Vue JS. I've got everything set up and have access to the json. What am I missing here:
JSON
{
"test": "example",
"data": [
{
"name": "My Name",
"address": "My Address"
}
]
}
Vue JS html
{{ someData['name'] }}
<ul>
<li v-for="item in someData" v-bind:key="item.id">
{{ item }}
</li>
</ul>
and my script:
created() {
this.$http.get('http://localhost:3000/properties.json').then(response => {
// get body data
this.someData = response.body
}, response => {
// error callback
});
}
The result I'm getting is:
As you can see, in my v-for simply specifying item grabs each of the items here, but I want to be able to do something like {{ item['name'] }} and {{ item['address'] }}
Upvotes: 0
Views: 444
Reputation: 9855
The crucial point is that the v-for="item in someData"
part in the component's view iterates over values of the someData
object, namely "John"
and "Jane"
.
Depending on what exactly is your goal, you should either reformat the JSON to be an array of objects (as suggested by @F.bernal), or change the logic of v-for
directive.
Upvotes: 0
Reputation: 2684
The main problem is in your JSON file. VueJS v-for is iterating over the keys in your JSON file, in this case {{ item }} will be getting name and address. That is the reason of your output.
To solve this...
Format your JSON file as
[{name: 'John', address: 'Jane'}]
Doing this your VueJS v-for will be iterating over JSON array and {{ item }} will get the value { name: 'John', address: 'Jane' } and now you can do {{ item.name }} {{ item.address }}
An example here
EDIT: Update your API request code
created() {
this.$http.get('http://localhost:3000/properties.json').then(response => {
// get body data
this.someData = [response.body]
}, response => {
// error callback
});
}
Upvotes: 2
Reputation: 114
You can simply do the following:
<template v-for="(item, key) in someData">
<span v-if="key == 'address'">{{item}}</span>
</template>
Upvotes: 0