Convert List into Array in JavaScript

Convert List into Array in JavaScript | Being a versatile and vast programming language, JavaScript has many functionalities that can be used to turn an entity into an array. The language itself has predefined versions of these techniques. Let’s examine the various methods used in JavaScript to transform objects into arrays.

Various kinds of techniques can be used in JavaScript to turn an object into an array. Object.keys(), Object.values(), and Object.entries() are a few of the available methods. To comprehend the techniques above, take a look at the examples below.

Convert List into Array in JavaScript Object.keys()

const planets = {
   first: 'Earth',
   last: 'Mars'
};

const propertyNames = Object.keys(planets);
console.log(propertyNames); 

Output:-

[ ‘first’, ‘last’ ]

Convert List into Array in JavaScript Object.values()

We can use Object.values() function to turn the planet object’s property values into an array:-

const planets = {
   first: 'Earth',
   last: 'Mars'
};

const propertyNames = Object.keys(planets);
console.log(propertyNames); 

Output:-

[ ‘Earth’, ‘Mars’ ]

To retrieve the attributes of the planets object, we utilized the Object.values() function in this method. The specified object planets are converted to an array using the Object.values() technique, and the results are displayed on the terminal.

Convert List into Array in JavaScript Object.entries()

const planets = {
   first: 'Earth',
   last: 'Mars'
};

const propertyNames = Object.entries(planets);
console.log(propertyNames); 

Output:-

[ [ ‘first’, ‘Earth’ ], [ ‘last’, ‘Mars’ ] ]

This method turns any object into an array, as seen in the results. The enumerable string-based attributes of the object are transformed into an array via the Object.entries() function. As Object.entries() appropriately specify every element of the entity in a fairer fashion, the result is generated in this way so that you may note which property is given to which string of the prescribed tasks during debugging.

These are a few of the methods used most frequently to change an object into an array. The techniques described above can also be jointly deployed to the characteristics of the objects and collectively specified into a single piece of code. They will all be changed into the appropriate arrays.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published.