0

I receive a response from a JSON API which contains the object locations each location has the same key, label. When I try to use a v-for loop I am unable to print out more than one of the locations. What is going on?

Response from API call

"locations": [
    {
      "label": "Brighton",
      "label": "London",
      "label": "Manchester",
    }
  ],

Template

<span v-for="(item, index) in locations" :key="index">
    <span v-if="index != 0">, </span>
    <span> {{ item.label }} </span>
</span>
Simon
  • 653
  • 3
  • 14
  • 25
  • Because, you have one element in locations array. When you ar using `v-for`, `for` is looking for array element. So `if` takes one element. – Musulmon Jul 15 '20 at 08:57
  • What is the correct way of doing it? @Musulmon – Simon Jul 15 '20 at 09:09
  • The best way is to change the server-side if you can. There is an another to convert JSON to array. `{ "label": "Brighton", "label": "London", "label": "Manchester", }` to `[ "label": "Brighton", "label": "London", "label": "Manchester", ]` – Musulmon Jul 15 '20 at 09:14
  • Try [that](https://stackoverflow.com/questions/19590865/from-an-array-of-objects-extract-value-of-a-property-as-array) to convert to array. – Musulmon Jul 15 '20 at 09:19
  • 1
    @Simon In JavaScript, such an object with only duplicate keys would be evaluated as an object that has only one key, where the last value wins. If the API provides the data as a string, you'll have to use a custom parser (other than `JSON.parse()`). – tony19 Jul 15 '20 at 09:27
  • Same parameter name is causing the issue. The last one is replacing the others, as musulmon said, it is the most suitable format. – Helper Jul 15 '20 at 12:00

0 Answers0