Open In App

How to get all property values of a JavaScript Object (without knowing the keys) ?

Method 1: Using Object.values() Method: The Object.values() method is used to return an array of the object’s own enumerable property values. The array can be looped using a for-loop to get all the values of the object. Therefore, the keys are not required to be known to get all the property values.

Syntax:






let valuesArray = Object.values(exampleObj);
  
for (let value of valuesArray) {
    console.log(value);
}

Example:




<!DOCTYPE html>
<html>
<head>
  <title>
    How to get all properties
    values of a Javascript Object
    (without knowing the keys)?
  </title>
</head>
<body>
  <h1 style="color: green">
    GeeksforGeeks
  </h1>
  <b>
    How to get all properties
    values of a Javascript Object
    (without knowing the keys)?
  </b>
  <p>
    Click on the button to get all
    properties values.
  </p>
  <p>
    Check the console for the output
  </p>
  <button onclick="getValues()">
    Get Property Values
  </button>
  <script type="text/javascript">
    function getValues() {
      let exampleObj = {
        language: "C++",
        designedby: "Bjarne Stroustrup",
        year: "1979"
      };
  
      let valuesArray = Object.values(exampleObj);
  
      for (let value of valuesArray) {
        console.log(value);
      }
    }
  </script>
</body>
</html>

Output:

Method 2: Extracting the keys to access the properties: The Object.keys() method is used to return an array of objects own enumerable property names. The forEach() method is used on this array to access each of the keys. The value of each property can be accessed using the keys with an array notation of the object.
Therefore, the keys are not required to be known beforehand to get all the property values.



Syntax:




let objKeys = Object.keys(exampleObj);
  
objKeys.forEach(key => {
    let value = exampleObj[key];
  
    console.log(value);
});

Example:




<!DOCTYPE html>
<html>
<head>
   <title>
    How to get all properties
    values of a Javascript Object
    (without knowing the keys)?
  </title>
</head>
<body>
  <h1 style="color: green">
    GeeksforGeeks
  </h1>
  <b>
    How to get all properties
    values of a Javascript Object
    (without knowing the keys)?
  </b>
  <p>
    Click on the button to get all
    properties values.
  </p>
  <p>
    Check the console for the output
  </p>
  <button onclick="getValues()">
    Get Property Values
  </button>
  <script type="text/javascript">
    function getValues() {
      let exampleObj = {
          language: "C++",
          designedby: "Bjarne Stroustrup",
          year: "1979"
        };
  
      let objKeys = Object.keys(exampleObj);
  
      objKeys.forEach(key => {
        let value = exampleObj[key];
  
        console.log(value);
      });
    }
  </script>
</body>
</html>

Output:


Article Tags :