These three methods provide different ways to iterate over object properties.
Object keys returns an array of all enumerable property names (keys) from an object. Use it when you need to know what properties exist, check if object is empty, or iterate over property names. Returns empty array for empty objects.
Object values returns an array of all enumerable property values. Use it when you need the values but not the keys, like summing numbers or collecting all data. Does not include property names.
Object entries returns an array of key value pairs, where each pair is a two element array. Use it when you need both keys and values, like converting to Map, filtering properties, or iterating with both. Can be converted back to object with Object fromEntries.
All three methods:
Only return own enumerable properties, not inherited ones. Return arrays in the same order properties were added. Are commonly used with array methods like map, filter, and forEach.
When to use what:
Use keys when you need property names. Use values when you only need the data. Use entries when you need both and want to transform or filter properties.
These methods are essential for working with objects in a functional programming style.
Example code
const person = {
name: 'John',
age: 30,
city: 'New York'
};
// Object.keys() - array of property names
const keys = Object.keys(person);
console.log(keys); // ['name', 'age', 'city']
// Check if empty
const isEmpty = Object.keys(person).length === 0;
// Iterate over keys
Object.keys(person).forEach(key => {
console.log(`${key}: ${person[key]}`);
});
// Object.values() - array of values
const values = Object.values(person);
console.log(values); // ['John', 30, 'New York']
// Sum numbers
const scores = {math: 90, english: 85, science: 95};
const total = Object.values(scores).reduce((sum, val) => sum + val, 0);
console.log(total); // 270
// Object.entries() - array of [key, value] pairs
const entries = Object.entries(person);
console.log(entries);
// [['name', 'John'], ['age', 30], ['city', 'New York']]
// Iterate with destructuring
for (const [key, value] of Object.entries(person)) {
console.log(`${key}: ${value}`);
}
// Filter properties
const filtered = Object.entries(person)
.filter(([key, value]) => typeof value === 'string')
.reduce((obj, [key, value]) => ({...obj, [key]: value}), {});
console.log(filtered); // {name: 'John', city: 'New York'}
// Convert to Map
const map = new Map(Object.entries(person));
// Convert back to object
const obj = Object.fromEntries(entries);
console.log(obj); // {name: 'John', age: 30, city: 'New York'}