How to Use JavaScript's Object.values() Function
Object.values()
is like Object.keys()
, except it returns an array containing all the object's values, instead of the object's keys.
const obj = { name: 'MasteringJS', location: 'Florida' };
Object.values(obj); // ['MasteringJS', 'Florida']
Why convert an object to an array of values?
So you can iterate through the object's own values easily.
For example, you can iterate through the object using forEach()
.
const obj = {
name: 'Jean-Luc Picard',
rank: 'Captain'
};
// Prints "Jean-Luc Picard" followed by "Captain"
Object.values(obj).forEach(val => {
console.log(val);
});
Only Own Properties
Object.values()
skips inherited properties - properties that are only defined on the object's prototype.
This is typically the correct behavior for POJOs, because you typically don't want Object.values()
to include the toString()
function.
But you may run into trouble if you're using Object.values()
on a class.
In the below example, Object.values()
does not return the value of the className
property, because className
is a getter on the class's prototype, not an own property of user
.
class User {
get className() {
return 'User';
}
constructor(name) {
this.name = name;
}
}
const user = new User('Jean-Luc Picard');
Object.keys(user); // ['Jean-Luc Picard'], no 'User'!
Enumerability
Object.values()
will only return the values of properties that are enumerable.
const obj = {
name: 'Jean-Luc Picard',
age: 59
};
Object.defineProperty(obj, 'hidden', {
enumerable: false,
value: true
});
obj.hidden // true
Object.values(obj); // ['Jean-Luc Picard', 59]
More Fundamentals Tutorials
- How to Add 2 Arrays Together in JavaScript
- The String `match()` Function in JavaScript
- Convert a Set to an Array in JavaScript
- What Does Setting the Length of a JavaScript Array Do?
- Get the Last Element in an Array in JavaScript
- Skip an Index in JavaScript Array map()
- Conditionally Add an Object to an Array in JavaScript