I'm having trouble accessing a data from an array using the index.
I've the following code in my template.
<a href="#" class="...">{{ fixture.flatOdds.data[0].market_id }}</a>
I'm having trouble accessing a data from an array using the index.
I've the following code in my template.
<a href="#" class="...">{{ fixture.flatOdds.data[0].market_id }}</a>
And that throws:
TypeError: fixture.flatOdds.data[0] is undefined
But fixture.flatOdds.data[0] is defined. When I print out the fixture.flatOdds.data[0] like this:
<a href="#" class="...">{{ fixture.flatOdds.data[0] }}</a>
It prints out the object just fine. The response,
{ "bookmaker_id": 2, "bookmaker_event_id": null, "market_id": 1, "odds": [ { "label": "1", "value": 3, "winning": null, "handicap": null, "total": null, "last_update": { "date": "2018-07-29 08:15:53.000000", "timezone_type": 3, "timezone": "UTC" } }, { "label": "X", "value": 3.2, "winning": null, "handicap": null, "total": null, "last_update": { "date": "2018-07-29 08:15:53.000000", "timezone_type": 3, "timezone": "UTC" } }, { "label": "2", "value": 2.38, "winning": null, "handicap": null, "total": null, "last_update": { "date": "2018-07-29 08:15:53.000000", "timezone_type": 3, "timezone": "UTC" } } ] }
What am I doing wrong?
Note: I am using axios to load the data from an API.
Share Improve this question edited Jul 30, 2018 at 6:03 Bereket Gobeze asked Jul 30, 2018 at 5:18 Bereket GobezeBereket Gobeze 3,4563 gold badges16 silver badges14 bronze badges2 Answers
Reset to default 1The problem most likely is that the value is undefined
at some point in the ponents lifecycle (you're probably loading it asynchronously). You are going to need be be defensive in the way that you reference your property.
You could use a puted property
const ponent = {
puted: {
marketId () {
if (this.fixture && this.fixture.flatOdds && this.fixture.flatOdds.data) {
return fixture.flatOdds.data[0].market_id
}
return 'unknown'
}
}
}
Or you could also use a filter,
<template>
<span>{{fixture | getMarketId}}</span>
</template>
<script>
export default {
filter: {
getMarketId (obj) {
if (obj && obj.flatOdds && obj.flatOdds.data) {
return obj.flatOdds.data[0].market_id
}
return 'unknown'
}
}
}
</script>
Or as per @ittus's example use a v-if
, but just be careful of which part of your object is undefined
.
Are you loading data asynchronously?
fixture.flatOdds.data[0]
might not be available when data is not loaded.
You can add v-if
to check if data is available.
<a href="#" class="..."
v-if="fixture.flatOdds.data[0]">
{{ fixture.flatOdds.data[0].market_id }}
</a>