To get an Object’s values as an array in JavaScript, you can use the Object.values() method passing the object as a parameter. The Object.values() method returns an array of values for the given object.
Let’s discuss this method in detail below.
Get An Object’s Values As Array In JavaScript
To get an Object’s values as an array in JavaScript, you can use the Object.values() method passing the object as a parameter. The Object.values() method returns an array of values for the given object.
For example, let’s consider the following object:
const obj = {
"name": "John",
"age": 30,
"city": "New York"
}
You can use the Object.values() method to get an array of values for the given object as follows:
const values = Object.values(obj);
console.log(values); // ['John', 30, 'New York']
As you can see from the above example, the Object.values() method returns an array of values for the given object.
The Object.values() method is not supported in Internet Explorer. You can use the Object.keys() method as a workaround.
Here is an example:
const obj = {
"name": "John",
"age": 30,
"city": "New York"
}
const values = Object.keys(obj).map(function(key) {
return obj[key];
});
console.log(values); // ['John', 30, 'New York']
In the above code, we have used the Object.keys() method to get an array of keys for the given object. Then, we have used the map() method to iterate over the array of keys and return an array of values by using obj[key] .
You can also use the Object.entries() method to get an array of key-value pairs for the given object as follows:
const obj = {
"name": "John",
"age": 30,
"city": "New York"
}
const entries = Object.entries(obj);
console.log(entries); // [['name', 'John'], ['age', 30], ['city', 'New York']]
As you can see from the above example, the Object.entries() method returns an array of key-value pairs for the given object.
You can also use the for…in loop to get an array of values for the given object as follows:
const obj = {
"name": "John",
"age": 30,
"city": "New York"
}
const values = [];
for(const key in obj) {
values.push(obj[key]);
}
console.log(values); // ['John', 30, 'New York']
In the above code, we have used the for…in loop to iterate over the keys of the given object. Then, we have pushed the values of the object into an array using obj[key] .
Conclusion
In this article, you have learned how to get an object’s values as an array in JavaScript. You can use the Object.values() method or the Object.keys() method along with the map() method to get an array of values for the given object.
You can also use the Object.entries() method to get an array of key-value pairs for the given object.
Alternatively, you can also use the for…in loop to get an array of values for the given object.
I hope this article was helpful and that you now know how to get an object’s values as an array in JavaScript. If you have any questions, please feel free to post them in the comments section below.
Happy coding! 🙂