How to Get All Property Values of a JavaScript Object

As a JavaScript developer, it is common to work with objects and their properties.

One frequent task is to retrieve the values of all properties in an object.

In this Javascript tutorial, we will discuss various ways to achieve this task.


For-in Loop

One of the simplest ways to get all property values of an object is by using a for-in loop.

This loop enumerates all the enumerable properties of an object, including its own and those inherited from its prototype.

The following code demonstrates the use of a for-in loop to get all the property values of an object.

const object = {
  name: 'John',
  age: 30,
  job: 'Developer'
};

const values = [];
for (const key in object) {
  values.push(object[key]);
}

console.log(values); // ['John', 30, 'Developer']

Object.values() Method

Another way to get all property values of an object is by using the Object.values() method.

This method returns an array of all the own enumerable property values of an object.

It was introduced in ECMAScript 2017 and is widely supported in modern browsers and Node.js.

The following code demonstrates the use of the Object.values() method to get all the property values of an object.

const object = {
  name: 'John',
  age: 30,
  job: 'Developer'
};

console.log(Object.values(object)); // ['John', 30, 'Developer']

Object.entries() Method

Another way to get all property values of an object is by using the Object.entries() method.

This method returns an array of arrays, where each inner array consists of a property name and its corresponding value.

The following code demonstrates the use of the Object.entries() method to get all the property values of an object.

const object = {
  name: 'John',
  age: 30,
  job: 'Developer'
};

const values = Object.entries(object).map(([key, value]) => value);

console.log(values); // ['John', 30, 'Developer']

Conclusion

In this tutorial, we discussed three ways to get all property values of a JavaScript object – using a for-in loop, the Object.values() method, and the Object.entries() method.

Choose the one that suits your requirements and fits your coding style.

Whether you are a beginner or an experienced JavaScript developer, these methods will help you get the job done efficiently.