0

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.

5
  • Could you check typeof this.results? Is it object or string? Commented Aug 30, 2019 at 11:16
  • yeah, maybe JSON.parse is needed here. Otherwise looks fine. Commented Aug 30, 2019 at 11:23
  • I'd think about the data structure for a moment. Nobody will understand "1:B" and so on. Besides writing code like this is pain. Commented Aug 30, 2019 at 11:31
  • response.data.items[0]['1:B']; should work. Something else is causing this issue. Commented Aug 30, 2019 at 12:03
  • skirtle using typeof reveals it is a string and sandrooco yes I agree however this data structure is used in someone else's api. Commented Aug 30, 2019 at 12:13

1 Answer 1

1

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'];
Sign up to request clarification or add additional context in comments.

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.