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)
})
})
CodePudding user response:
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);
CodePudding user response:
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);