Tommy Tang
Tommy Tang

Reputation: 239

vue js axios response to array list

i am working a typeahead. and my typeahead accept a array list like ['Canada', 'USA', 'Mexico']. and now i have a axios api to get a list of country. but i don't know how can i convert to a array list. Now work if hardcode a country list.

<vue-bootstrap-typeahead
 :data="addresses"
 v-model="addressSearch"
/>
data() {
 return {
  addresses: ['Canada', 'USA', 'Mexico'],
  addressSearch: '',
 }
},
axios.get('api_link', {})
  .then(function (response) {
  //How can i create a array list from api return useing name like addresses?
})

And my api return: [ { "id": 1, "name": "Canada" }, { "id": 2, "name": "USA" }, ]

Upvotes: 3

Views: 7030

Answers (2)

Eder D&#237;az
Eder D&#237;az

Reputation: 2071

You can use array.map to take only the names like this:

axios.get('api_link', {})
  .then((response) => {
    this.addresses = response.data.map(country => country.name)
  })

Upvotes: 1

connexo
connexo

Reputation: 56823

Make use of the created() lifecycle hook to get the data:

created() {
  axios.get('api_link', {})
    .then((response) => { this.addresses = response.data.map(x => x.name) })
}

In your data() make sure to initialize to an empty array:

data() {
  return {
    addresses: [],
    ...
}

Just so you see what the map function does:

console.log([ { "id": 1, "name": "Canada" }, { "id": 2, "name": "USA" }, ].map(x=>x.name))

Upvotes: 9

Related Questions