JavaScript provides three powerful built-in methods for working with object properties: Object.keys(), Object.values(), and Object.entries(). These methods convert object properties into arrays, enabling you to use all array methods for iteration, transformation, and manipulation. They're essential for modern JavaScript development and are widely used in real-world applications. Let's master these fundamental object manipulation tools!
Why These Methods Matter
Objects aren't directly iterable like arrays. These methods solve this by converting object properties into arrays.
Modern methods are cleaner and more powerful
Traditional Approach
// Traditional way: for...in loop
let user = {
name: "Alice",
age: 25,
email: "alice@test.com"
};
// Iterate with for...in
for (let key in user) {
console.log(key, user[key]);
}
// Can't use array methods
// user.map() // Error!
// user.filter() // Error!
// Manual array conversion needed
let keys = [];
for (let key in user) {
keys.push(key);
}
console.log(keys);Modern Approach
// Modern way: Object.keys/values/entries
let user = {
name: "Alice",
age: 25,
email: "alice@test.com"
};
// Get array of keys
let keys = Object.keys(user);
console.log(keys);
// ["name", "age", "email"]
// Now use array methods!
keys.forEach(key => {
console.log(key, user[key]);
});
// Or get values directly
let values = Object.values(user);
console.log(values);
// ["Alice", 25, "alice@test.com"]Benefits:
- Convert objects to arrays for iteration
- Use all array methods (map, filter, reduce, etc.)
- Cleaner, more functional code
- No need for for...in loops
- Works with modern JavaScript patterns
Object.keys() - Get Property Names
Object.keys() returns an array of an object's own enumerable property names (keys).
Basic Usage
let person = {
name: "Alice",
age: 25,
email: "alice@test.com",
city: "NYC"
};
// Get all keys
let keys = Object.keys(person);
console.log(keys);
// ["name", "age", "email", "city"]
// It's a real array!
console.log(Array.isArray(keys)); // true
console.log(keys.length); // 4
// Use array methods
keys.forEach(key => {
console.log(`${key}: ${person[key]}`);
});
// Output:
// name: Alice
// age: 25
// email: alice@test.com
// city: NYC
// Empty object
let empty = {};
console.log(Object.keys(empty)); // []Common Patterns with Object.keys()
let product = {
id: 1,
name: "Laptop",
price: 1000,
category: "Electronics",
inStock: true
};
// 1. Count properties
let propertyCount = Object.keys(product).length;
console.log("Properties:", propertyCount); // 5
// 2. Check if object has properties
let isEmpty = Object.keys(product).length === 0;
console.log("Is empty?", isEmpty); // false
// 3. Check if property exists
let hasPrice = Object.keys(product).includes("price");
console.log("Has price?", hasPrice); // true
// 4. Get specific keys (filter)
let stringProps = Object.keys(product).filter(key => {
return typeof product[key] === "string";
});
console.log("String properties:", stringProps);
// ["name", "category"]
// 5. Transform keys (map)
let upperKeys = Object.keys(product).map(key => key.toUpperCase());
console.log("Uppercase keys:", upperKeys);
// ["ID", "NAME", "PRICE", "CATEGORY", "INSTOCK"]
// 6. Find property
let firstLongKey = Object.keys(product).find(key => key.length > 5);
console.log("First long key:", firstLongKey); // "category"Creating New Objects from Keys
let user = {
name: "Alice",
age: 25,
email: "alice@test.com",
password: "secret123",
role: "admin"
};
// Remove sensitive data
let safeKeys = Object.keys(user).filter(key => key !== "password");
let safeUser = {};
safeKeys.forEach(key => {
safeUser[key] = user[key];
});
console.log(safeUser);
// { name: "Alice", age: 25, email: "alice@test.com", role: "admin" }
// Or use reduce (more functional)
let safeUser2 = Object.keys(user)
.filter(key => key !== "password")
.reduce((obj, key) => {
obj[key] = user[key];
return obj;
}, {});
console.log(safeUser2);Object.values() - Get Property Values
Object.values() returns an array of an object's own enumerable property values.
Basic Usage
let person = {
name: "Alice",
age: 25,
email: "alice@test.com",
city: "NYC"
};
// Get all values
let values = Object.values(person);
console.log(values);
// ["Alice", 25, "alice@test.com", "NYC"]
// It's a real array!
console.log(Array.isArray(values)); // true
console.log(values.length); // 4
// Use array methods
values.forEach(value => {
console.log(value);
});
// Empty object
let empty = {};
console.log(Object.values(empty)); // []Common Patterns with Object.values()
let scores = {
math: 85,
english: 92,
science: 78,
history: 88
};
// 1. Sum all values
let total = Object.values(scores).reduce((sum, score) => sum + score, 0);
console.log("Total:", total); // 343
// 2. Average
let average = total / Object.values(scores).length;
console.log("Average:", average.toFixed(2)); // 85.75
// 3. Find max/min
let highest = Math.max(...Object.values(scores));
let lowest = Math.min(...Object.values(scores));
console.log("Highest:", highest); // 92
console.log("Lowest:", lowest); // 78
// 4. Check if any value meets condition
let hasHighScore = Object.values(scores).some(score => score > 90);
console.log("Has score > 90?", hasHighScore); // true
// 5. Check if all values meet condition
let allPassing = Object.values(scores).every(score => score >= 60);
console.log("All passing?", allPassing); // true
// 6. Filter values
let highScores = Object.values(scores).filter(score => score >= 85);
console.log("High scores:", highScores); // [85, 92, 88]
// 7. Count occurrences
let products = {
laptop: "Electronics",
mouse: "Electronics",
shirt: "Clothing",
phone: "Electronics"
};
let electronics = Object.values(products).filter(cat => cat === "Electronics").length;
console.log("Electronics count:", electronics); // 3Working with Different Value Types
let data = {
name: "Alice",
age: 25,
active: true,
scores: [85, 92, 78],
address: { city: "NYC" }
};
let values = Object.values(data);
console.log(values);
// ["Alice", 25, true, [85, 92, 78], { city: "NYC" }]
// Check value types
values.forEach(value => {
console.log(typeof value, value);
});
// Output:
// string Alice
// number 25
// boolean true
// object [85, 92, 78]
// object { city: "NYC" }
// Filter by type
let strings = Object.values(data).filter(val => typeof val === "string");
console.log("Strings:", strings); // ["Alice"]
let numbers = Object.values(data).filter(val => typeof val === "number");
console.log("Numbers:", numbers); // [25]Object.entries() - Get Key-Value Pairs
Object.entries() returns an array of [key, value] pairs for each property.
Basic Usage
let person = {
name: "Alice",
age: 25,
email: "alice@test.com"
};
// Get all entries
let entries = Object.entries(person);
console.log(entries);
// [
// ["name", "Alice"],
// ["age", 25],
// ["email", "alice@test.com"]
// ]
// Each entry is [key, value] array
entries.forEach(entry => {
console.log(entry);
console.log("Key:", entry[0]);
console.log("Value:", entry[1]);
});
// Destructure in loop (cleaner!)
entries.forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});
// Output:
// name: Alice
// age: 25
// email: alice@test.comCommon Patterns with Object.entries()
let product = {
name: "Laptop",
price: 1000,
category: "Electronics",
inStock: true
};
// 1. Filter entries
let cheapProducts = Object.entries(product).filter(([key, value]) => {
return key === "price" && value < 500;
});
console.log(cheapProducts); // [] (price is 1000)
// 2. Transform entries
let upperCaseEntries = Object.entries(product).map(([key, value]) => {
return [key.toUpperCase(), value];
});
console.log(upperCaseEntries);
// [["NAME", "Laptop"], ["PRICE", 1000], ...]
// 3. Find entry
let priceEntry = Object.entries(product).find(([key]) => key === "price");
console.log(priceEntry); // ["price", 1000]
// 4. Convert back to object
let obj = Object.fromEntries(upperCaseEntries);
console.log(obj);
// { NAME: "Laptop", PRICE: 1000, ... }
// 5. Create object from filtered entries
let numericOnly = Object.fromEntries(
Object.entries(product).filter(([key, value]) => typeof value === "number")
);
console.log(numericOnly); // { price: 1000 }Object.fromEntries() - Convert Entries Back
// Convert entries array back to object
let entries = [
["name", "Alice"],
["age", 25],
["email", "alice@test.com"]
];
let obj = Object.fromEntries(entries);
console.log(obj);
// { name: "Alice", age: 25, email: "alice@test.com" }
// Practical: Transform object properties
let prices = {
laptop: 1000,
mouse: 25,
keyboard: 75
};
// Apply discount to all prices
let discounted = Object.fromEntries(
Object.entries(prices).map(([item, price]) => {
return [item, price * 0.9]; // 10% off
})
);
console.log(discounted);
// { laptop: 900, mouse: 22.5, keyboard: 67.5 }
// Swap keys and values
let swapped = Object.fromEntries(
Object.entries(prices).map(([key, value]) => [value, key])
);
console.log(swapped);
// { 1000: "laptop", 25: "mouse", 75: "keyboard" }Comparing the Three Methods
| Method | Returns | Use Case |
|---|---|---|
Object.keys() | Array of keys | When you need property names |
Object.values() | Array of values | When you only need values |
Object.entries() | Array of [key, value] | When you need both keys and values |
let user = {
name: "Alice",
age: 25,
email: "alice@test.com"
};
// Object.keys()
console.log(Object.keys(user));
// ["name", "age", "email"]
// Object.values()
console.log(Object.values(user));
// ["Alice", 25, "alice@test.com"]
// Object.entries()
console.log(Object.entries(user));
// [["name", "Alice"], ["age", 25], ["email", "alice@test.com"]]
// All return arrays in same order
Object.keys(user).forEach((key, index) => {
let value = Object.values(user)[index];
let [entryKey, entryValue] = Object.entries(user)[index];
console.log(`${key} = ${value} = ${entryKey}:${entryValue}`);
});Practical Examples
Example 1: Object Transformation
// Transform all numeric values
function multiplyNumericValues(obj, multiplier) {
return Object.fromEntries(
Object.entries(obj).map(([key, value]) => {
if (typeof value === "number") {
return [key, value * multiplier];
}
return [key, value];
})
);
}
let prices = {
laptop: 1000,
mouse: 25,
category: "Electronics",
inStock: true
};
let doubled = multiplyNumericValues(prices, 2);
console.log(doubled);
// { laptop: 2000, mouse: 50, category: "Electronics", inStock: true }
// Filter and transform
function getNumericProperties(obj) {
return Object.fromEntries(
Object.entries(obj).filter(([key, value]) => typeof value === "number")
);
}
let numericOnly = getNumericProperties(prices);
console.log(numericOnly); // { laptop: 1000, mouse: 25 }Example 2: Object Comparison
function compareObjects(obj1, obj2) {
// Check if same number of properties
let keys1 = Object.keys(obj1);
let keys2 = Object.keys(obj2);
if (keys1.length !== keys2.length) {
return false;
}
// Check if all keys and values match
return keys1.every(key => {
return obj2.hasOwnProperty(key) && obj1[key] === obj2[key];
});
}
let user1 = { name: "Alice", age: 25 };
let user2 = { name: "Alice", age: 25 };
let user3 = { name: "Bob", age: 30 };
console.log(compareObjects(user1, user2)); // true
console.log(compareObjects(user1, user3)); // false
// Find differences between objects
function findDifferences(obj1, obj2) {
let differences = {};
Object.keys(obj1).forEach(key => {
if (obj1[key] !== obj2[key]) {
differences[key] = {
old: obj1[key],
new: obj2[key]
};
}
});
return differences;
}
let oldConfig = { host: "localhost", port: 3000, ssl: false };
let newConfig = { host: "example.com", port: 3000, ssl: true };
console.log(findDifferences(oldConfig, newConfig));
// {
// host: { old: "localhost", new: "example.com" },
// ssl: { old: false, new: true }
// }Example 3: Data Summarization
function summarizeData(data) {
let keys = Object.keys(data);
let values = Object.values(data);
return {
propertyCount: keys.length,
properties: keys,
valueTypes: values.reduce((types, value) => {
let type = typeof value;
types[type] = (types[type] || 0) + 1;
return types;
}, {}),
numericStats: (() => {
let numbers = values.filter(v => typeof v === "number");
if (numbers.length === 0) return null;
return {
count: numbers.length,
sum: numbers.reduce((a, b) => a + b, 0),
average: numbers.reduce((a, b) => a + b, 0) / numbers.length,
min: Math.min(...numbers),
max: Math.max(...numbers)
};
})(),
isEmpty: keys.length === 0
};
}
let product = {
name: "Laptop",
price: 1000,
stock: 15,
rating: 4.5,
category: "Electronics"
};
console.log(summarizeData(product));
// {
// propertyCount: 5,
// properties: ["name", "price", "stock", "rating", "category"],
// valueTypes: { string: 2, number: 3 },
// numericStats: {
// count: 3,
// sum: 1019.5,
// average: 339.83,
// min: 4.5,
// max: 1000
// },
// isEmpty: false
// }Object.keys/values/entries Practice
Experiment with object iteration methods
console.log() to see your output in the console above.Key Takeaways
Object.keys(obj)returns array of property namesObject.values(obj)returns array of property valuesObject.entries(obj)returns array of [key, value] pairs- All three return real arrays—use all array methods!
Object.fromEntries()converts entries back to object- Great for iterating, filtering, and transforming objects
- Order is consistent across all three methods
- Use entries when you need both keys and values
- Perfect for object validation, comparison, and transformation
- More functional and cleaner than for...in loops
What's Next?
You now understand Object.keys(), Object.values(), and Object.entries()— essential methods for working with object properties! These methods enable powerful functional programming patterns and make object manipulation much more elegant.
In the final lesson of the Objects section, we'll explore the Spread Operator and Object Cloning—learning how to copy objects, merge them, and understand shallow vs deep copying. This completes your object manipulation toolkit!
💪 Practice Challenge:
Before moving on, try creating:
- A function that counts how many properties of each type an object has
- Transform an object by doubling all numeric values using entries
- Compare two objects and return which properties are different
- Filter an object to keep only properties with string values
- Calculate statistics (sum, average, min, max) from an object's numeric values