Object.values() returns an array of values of all enumerable properties of an object. Unlike for…in, it doesn’t iterate inherited properties and returns values directly, not keys.
const user = { name: 'John', age: 25 };
const values = Object.values(user);
console.log(values); // ['John', 25]Object.values() is a method to get all property values of an object. It’s simple and convenient when you need to work only with values, not keys.
Returns array of property values:
const user = { name: 'John', age: 25 };
const values = Object.values(user);
console.log(values); // ['John', 25]const obj = { a: 1, b: 2, c: 3 };
console.log(Object.values(obj)); // [1, 2, 3]const obj = { name: 'John' };
// Doesn't include toString, hasOwnProperty and other inherited methodsconst user = {
name: 'John',
age: 25,
city: 'Moscow'
};
const values = Object.values(user);
console.log(values); // ['John', 25, 'Moscow']const scores = { math: 5, physics: 4, chemistry: 5 };
// Sum of all scores
const total = Object.values(scores).reduce((sum, score) => sum + score, 0);
console.log(total); // 14// Order is same as in for...in
const obj = { 3: 'three', 1: 'one', 2: 'two', a: 'letter' };
console.log(Object.values(obj)); // ['one', 'two', 'three', 'letter']const obj = { name: 'John' };
// Hide property
Object.defineProperty(obj, 'hidden', {
value: 'secret',
enumerable: false
});
console.log(Object.values(obj)); // ['John'] - hidden not visibleconst user = { name: 'John', age: 25 };
// ❌ Complex way
const values1 = [];
for (let key in user) {
if (user.hasOwnProperty(key)) {
values1.push(user[key]);
}
}
// ✅ Simple way
const values2 = Object.values(user);const prices = { apple: 100, banana: 50, orange: 80 };
// Find maximum price
const maxPrice = Math.max(...Object.values(prices));
console.log(maxPrice); // 100// ❌ Thinking we get keys
const obj = { a: 1, b: 2 };
const result = Object.values(obj);
console.log(result); // [1, 2] - values, not keys!
// ✅ For keys use Object.keys()
const keys = Object.keys(obj);
console.log(keys); // ['a', 'b']// ❌ Trying to use with primitives
Object.values(42); // Error!
// ✅ Only with objects
Object.values({ value: 42 }); // [42]Object.values() is convenient when you need to work only with object property values. It’s simpler than for…in and doesn’t require inheritance checks.
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪