Open In App

How to Get all Property Values of a JavaScript Object without knowing the Keys?

Last Updated : 14 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To get all property values from a JavaScript object without knowing the keys involves accessing the object’s properties and extracting their values.

Below are the approaches to get all property values of a JavaScript Object:

Approach 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: This example shows the use of the above-explained approach.

JavaScript
let exampleObj = {
  language: "JavaScript",
  designedby: "Brendan Eich",
  year: "1995"
};

let valuesArray = Object.values(exampleObj);

for (let value of valuesArray) {
  console.log(value);
}

Output
JavaScript
Brendan Eich
1995

Approach 2: Using Object.keys() method

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:This example shows the implementation of the above-explained approach.

JavaScript
let exampleObj = {
  language: "JavaScript",
  designedby: "Brendan Eich",
  year: "1995"
};

let objKeys = Object.keys(exampleObj);

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

Output
JavaScript
Brendan Eich
1995


Similar Reads