Reputation: 117
In a .vue file I am trying the get value from an axios get response result which is in a nested array. The code looks like the example below (without a search form for query).
<div class="results" v-if="results">
<p>{{ results }}</p>
<p>{{ result }}</p>
</div>
<script>
import axios from 'axios';
export default {
name: 'search',
data () {
return {
query '',
results: '',
result: ''
}
},
methods: {
getResults(query) {
axios.get('https://apiexample.com/api/search.php?t_id=' + query).then( response => {
this.results = response.data.items;
this.result = response.data.items[0]['1:B'];
});
}
}
}
So for this.results I get something similar to
[{"1:A":10,"1:B":20,"1:C":30,"1:D":40,"1:E":50},
{"1:A":20,"1:B":30,"1:C":40,"1:D":50,"1:E":60},
{"1:A":30,"1:B":40,"1:C":50,"1:D":60,"1:E":70},
{"1:A":40,"1:B":50,"1:C":60,"1:D":70,"1:E":80}]
For this.result I am getting undefined when I am trying to get the value of 20. Probably navigating that type of response incorrectly or perhaps something more specific needs to be added to data() {}?
Any help would be appreciated.
Thanks.
Upvotes: 0
Views: 1728
Reputation: 29092
As noted in the comments, response.data.items
is a string, not an object. This seems like a flawed API response, with the items
unnecessarily encoded as a JSON string within the response.
However, assuming that fixing the problem in the server is not possible, the items
can be decoded in the UI:
this.results = JSON.parse(response.data.items);
this.result = this.results[0]['1:B'];
Upvotes: 1