Computer >> Computer tutorials >  >> Programming >> Javascript

How to return an array whose elements are the enumerable property values of an object in JavaScript?


We can use some logical methods to get the values and also keys from an object, but those methods will not return the values as an array, which is very useful in many cases. Javascript has provided 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 nothing but the property values of the object.

Example-1

In the following example, an object is sent through the method object.values() and the property values were 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>

Output

true
1,2,3

Example-2

In the following example, an object is sent through the method object.values() and the property values were displayed as an array. Array.isArray() is used to check whether the resulted object is an array or not.

<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>

Output

true
Elon,Tesla,47,1 Billion dollars