Azim
Azim

Reputation: 47

How to return variable as array in vuejs

I am trying to return a variable as an array like [ 'Google', 'Facebook', 'Twitter', 'Apple', 'Oracle' ]

But what I am getting is

Google
Facebook
Twitter
Barishal
Oracle

My code from setup() :

const stringOptions = axios.get('https://api.com').then(response 
 => {
        Object.keys(response.data.divisions).forEach(key => {
          var a = response.data.divisions[key].name
          console.log(a)
        })
    })

Upvotes: 1

Views: 700

Answers (2)

Amaarockz
Amaarockz

Reputation: 4684

Another approach using Object.values along with Array.map()

const divisions = {
  0: {
    name: 'Google'
  },
  1: {
    name: 'Facebook'
  },
  2: {
    name: 'Twitter'
  },
  3: {
    name: 'Barishal'
  },
  4: {
    name: 'Oracle'
  }
};

const res = Object.values(divisions).map(division => division.name);

console.log(res);

Upvotes: 1

Rohìt Jíndal
Rohìt Jíndal

Reputation: 27222

You can simply achieve this by using Object.keys() along with Array.map() method.

Try this :

const divisions = {
  0: {
    name: 'Google'
  },
  1: {
    name: 'Facebook'
  },
  2: {
    name: 'Twitter'
  },
  3: {
    name: 'Barishal'
  },
  4: {
    name: 'Oracle'
  }
};

const res = Object.keys(divisions).map(key => divisions[key].name);

console.log(res);

Upvotes: 3

Related Questions