Transforming an object into an array

Asked

Viewed 143 times

-1

I have the return of such an object:

response = {
    1: "Julio",
    2: "Rubens",
    3: "Narciso",
    4: "Elton",
    5: "Junior"
}

and would like to create an array with all names, e.g.:

array = ["Julio", "Rubens", "Narciso", "Elton", "Junior"]

Note: Sometimes returns more or less names.

  • What do you mean "Sometimes it returns more or less names"? Could [Edit] the question with the code? - however, tried with Object.values(response)?

1 answer

1

A very basic way is to loop the object to populate an array:

const response = {
    1: "Julio",
    2: "Rubens",
    3: "Narciso",
    4: "Elton",
    5: "Junior"
}

const array = [];

for (const key in response)
  array.push(response[key]);

console.log(array);

But there’s a native method that does it for you, the Object.values:

const response = {
    1: "Julio",
    2: "Rubens",
    3: "Narciso",
    4: "Elton",
    5: "Junior"
}

const array = Object.values(response);

console.log(array);

You can see his compatibility on Can I use

Browser other questions tagged

You are not signed in. Login or sign up in order to post.