Hello devs,
In this tutorial, I will show you how to convert an object to an array in javascript. To show you that javascript object conversion, I will use some dummy data so that you can understand it better. You know that sometimes we need to convert an object to an only array with values or keys from that array object.
You know that javascript has a built int function to convert that and those are Object.keys()
, Object.values()
, and Object.entries()
and we will use them. Let assume we have the below data:
const animal = {
name: 'Lion',
designation: 'King'
};
Now let assume we want to make an array with the keys from that object
const propertyNames = Object.keys(animal);
console.log(propertyNames);
Then the output will look like this:
[ 'name', 'designation' ]
Now to convert the property’s values of the animal object to an array, you use the Object.values()
method:
const propertyValues = Object.values(animal);
console.log(propertyValues);
Then the output will look like this:
[ 'Lion', 'King' ]
Now we want to convert the enumerable string-keyed properties of an object to an array, you use the Object.entries()
method. For example:
const entries = Object.entries(animal);
console.log(entries);
Then the output will look like this:
[ [ 'name', 'designation' ], [ 'Lion', 'King' ] ]
Read also: JavaScript Pass Function as Parameter with Example
Hope this tutorial can help you.
#javascript