The Object.entries()
and Object.values()
methods are both used to extract data from an object in JavaScript, but they do so in different ways.
The Object.entries()
method returns an iterable of key-value pairs from an object. It takes an object as its argument and returns an iterator function that yields an array of arrays, where each inner array contains a key and its corresponding value:
const obj = {
key1: 'value1',
key2: 'value2'
};
for ([key, value] of Object.entries(obj)) {
console.log(`Key ${key} has value ${value}`);
}
This will output:
Key key1 has value value1
Key key2 has value value2
The Object.values()
method, on the other hand, returns an array of all the values from an object. It takes an object as its argument and returns an array containing all the values:
const obj = {
key1: 'value1',
key2: 'value2'
};
console.log(Object.values(obj));
This will output:
[ 'value1', 'value2' ]
Here's an example of when you might use Object.entries()
vs. Object.values()
:
const obj = {
name: 'John Doe',
age: 30,
email: '[email protected]'
};
// Use Object.entries() to get key-value pairs
for ([key, value] of Object.entries(obj)) {
console.log(`Key ${key} has value ${value}`);
}
// Use Object.values() to get an array of values
console.log(Object.values(obj));
This will output:
Key name has value John Doe
Key age has value 30
Key email has value [email protected]
[ 'John Doe', 30, '[email protected]' ]