Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to return an array whose elements are the enumerable property values of an object in JavaScript?
We can use various methods to get values and keys from an object, but those methods will not return the values as an array, which is very useful in many cases. JavaScript provides the Object.values() method to get an array whose elements are the enumerable property values of an object.
Syntax
Object.values(obj);
This method takes an object as an argument and returns an array whose elements are the property values of the object.
Parameters
obj: The object whose enumerable property values are to be returned.
Return Value
An array containing the values of all enumerable properties of the given object, in the same order as provided by a for...in loop.
Example 1: Basic Usage
In the following example, an object is passed through the Object.values() method and the property values are displayed as an array.
<html>
<body>
<script>
var obj = {"one": 1, "two": 2, "three": 3};
document.write(Array.isArray(Object.values(obj)));
document.write("<br>");
document.write(Object.values(obj));
</script>
</body>
</html>
true 1,2,3
Example 2: Object with String Values
In the following example, an object with string values is processed using Object.values(). The Array.isArray() method confirms that the result is indeed an array.
<html>
<body>
<script>
var object = {"name": "Elon", "company": "Tesla", "age": "47", "property": "1 Billion dollars"};
document.write(Array.isArray(Object.values(object)));
document.write("<br>");
document.write(Object.values(object));
</script>
</body>
</html>
true Elon,Tesla,47,1 Billion dollars
Example 3: Working with Mixed Data Types
Object.values() works with objects containing different data types including numbers, strings, booleans, and arrays.
<html>
<body>
<script>
var mixedObj = {
id: 101,
name: "JavaScript",
active: true,
tags: ["programming", "web"]
};
var values = Object.values(mixedObj);
document.write("Values: " + values);
document.write("<br>");
document.write("Length: " + values.length);
</script>
</body>
</html>
Values: 101,JavaScript,true,programming,web Length: 4
Key Points
- Object.values() only returns enumerable properties
- The order of values matches the order of properties in the object
- It works with all data types including nested objects and arrays
- The method returns an empty array for empty objects
Browser Compatibility
Object.values() is supported in all modern browsers including Chrome 54+, Firefox 47+, Safari 10.1+, and Edge 14+.
Conclusion
Object.values() provides a clean and efficient way to extract all enumerable property values from an object as an array. This method is particularly useful when you need to iterate over object values or perform array operations on them.
