How to get the values of an object in JavaScript?

Java

There are some methods such as Object.values() to get the values of an object. But through those methods, the process to find out the values is lengthy. To alleviate this, Underscore.js a library of javascript has provided a method called _.values(). This method requires no for loop to execute the values. It is a direct method to execute the values of an object. 

In the following example, the values of an object were executed using the Object.values() method. This method requires a for-loop to execute the values.

Example

Live Demo

<html>
<body>
<script>
   var user = {
      name: "Rahim",
      designation: "content developer"
   };
   for (let value of Object.values(user)) {
      document.write(value + "</br>");
   }
</script>
</body>
</html>

Output

Rahim
content developer

In the following example, the values of an object were executed using _.values() method. Here no for-loop is required. It's a straight forward method.

Example

Live Demo

<html>
<body>
<script
src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script>
</head>
<body>
   <script>
      var res = JSON.stringify(_.values({"name": 'ElonMusk',age: 47, "Organization":'Spacex' }));
      document.write((res));
   </script>
</body>
</html>

Output

["ElonMusk",47,"Spacex"]
raja
Published on 11-Jul-2019 18:12:10
Advertisements