1

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)
        })
    })
3
  • 1
    can u do axios.get(/*...*/).then(response => response.text()).then(data => console.log(data)) and post the result here? Commented Aug 2, 2022 at 12:45
  • 3
    return Object.keys(response.data.divisions).map((key) => response.data.divisions[key].name) Commented Aug 2, 2022 at 12:46
  • 1
    @MichalLevý Thanks a lot ! Have great day ... unfortunately I can't upvote since my reputation is near 0 :) Commented Aug 2, 2022 at 12:50

2 Answers 2

3

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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);

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.