0
0
JavascriptHow-ToBeginner · 3 min read

How to Get All Values of Object in JavaScript Easily

Use the Object.values() method to get an array of all values from an object in JavaScript. It extracts only the values, ignoring keys, and returns them in the order they appear in the object.
📐

Syntax

The Object.values() method takes a single object as an argument and returns an array containing all the values of that object.

  • Object.values(obj): obj is the object you want to get values from.
  • The returned array contains the values in the same order as the object's keys.
javascript
const valuesArray = Object.values(obj);
💻

Example

This example shows how to get all values from a simple object and print them.

javascript
const person = {
  name: 'Alice',
  age: 30,
  city: 'New York'
};

const values = Object.values(person);
console.log(values);
Output
["Alice", 30, "New York"]
⚠️

Common Pitfalls

One common mistake is trying to get values by looping over the object directly, which can be error-prone or verbose. Another is confusing Object.values() with Object.keys() or Object.entries(). Also, Object.values() only gets enumerable own properties, so inherited or non-enumerable properties are ignored.

javascript
const obj = { a: 1, b: 2 };

// Wrong: Trying to get values by looping keys manually
const valuesWrong = [];
for (const key in obj) {
  valuesWrong.push(obj[key]); // This pushes values, not keys
}

// Right: Use Object.values()
const valuesRight = Object.values(obj);

console.log('Wrong:', valuesWrong); // [1, 2]
console.log('Right:', valuesRight); // [1, 2]
Output
Wrong: [1, 2] Right: [1, 2]
📊

Quick Reference

MethodDescriptionReturns
Object.values(obj)Gets all values of own enumerable propertiesArray of values
Object.keys(obj)Gets all keys of own enumerable propertiesArray of keys
Object.entries(obj)Gets all key-value pairs as arraysArray of [key, value] arrays

Key Takeaways

Use Object.values(obj) to get an array of all values from an object.
Object.values() returns values in the order of the object's keys.
It only includes the object's own enumerable properties, not inherited ones.
Avoid manually looping keys to get values; Object.values() is simpler and safer.
Remember related methods: Object.keys() for keys and Object.entries() for key-value pairs.