Object.values
Prior to ES2017, you use a for...in
loop and Object.hasOwnProperty()
method to access values of own enumerable properties of an object. For example:
const person = {
firstName: 'John',
lastName: 'Doe',
age: 25
};
for (const key in person) {
if (person.hasOwnProperty(key)) {
const value = person[key];
console.log(value);
}
}
Output:
John
Doe
25
ES2017 introduces a new method called Object.values()
that allows you to return an array of own enumerable property’s values of an object.
The following shows the syntax of the Object.values()
:
Object.values(obj)
The Object.values()
accepts an object and returns its own enumerable property’s values as an array. See the following example:
const person = {
firstName: 'John',
lastName: 'Doe',
age: 25
};
const profile = Object.values(person);
console.log(profile);
Output:
[ 'John', 'Doe', 25 ]
Object.values()
vs. for...in
The Object.values()
returns own enumerable properties while the for...in
loop iterates properties in the prototype chain.
Technically, if you use the for...in
loop with the Object.hasOwnProperty()
method, you will get the same set of values as the Object.values()
.
Introduction to JavaScript Object.entries()
method
ES2017 introduces the Object.entries()
method that accepts an object and returns its own enumerable string-keyed property [key, value]
pairs of the object.
Here is the syntax of the Object.entries()
method:
Object.entries()
See the following example:
const ssn = Symbol('ssn');
const person = {
firstName: 'John',
lastName: 'Doe',
age: 25,
[ssn]: '123-345-789'
};
const kv = Object.entries(person);
console.log(kv);
Output:
[
['firstName', 'John'],
['lastName', 'Doe'],
['age', 25]
]
In this example:
- The firstName, lastName, and age are own enumerable string-keyed property of the person object, therefore, they are included in the result.
- The
ssn
is not a string-key property of the person object, so it is not included in the result.
Object.entries()
vs. for...in
The main difference between the Object.entries()
and the for...in
loop is that the for...in
loop also enumerates object properties in the prototype chain.