Object.keys(), values(), entries() & Iteration
Object.keys(), Object.values(), and Object.entries() convert objects into arrays for iteration. These methods are essential for processing, transforming, and displaying object data.
Object Iteration Methods
- Object.keys(obj) — Returns array of property names: ['name', 'age', 'email']
- Object.values(obj) — Returns array of values: ['Alice', 25, 'alice@email.com']
- Object.entries(obj) — Returns array of [key, value] pairs: [['name','Alice'], ['age',25]]
- Object.assign(target, source) — Copy/merge objects (like spread but mutates target)
- Object.freeze(obj) — Prevents all modifications. Properties can't be added, removed, or changed
- Object.fromEntries(entries) — Convert entries back to object
Object Iteration Code
const user = { name: "Alice", age: 25, role: "admin" };
// Object.keys
console.log(Object.keys(user)); // ["name", "age", "role"]
// Object.values
console.log(Object.values(user)); // ["Alice", 25, "admin"]
// Object.entries — most useful for iteration
Object.entries(user).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});
// Transform object
const uppercased = Object.fromEntries(
Object.entries(user).map(([k, v]) => [k, String(v).toUpperCase()])
);
console.log(uppercased); // { name: "ALICE", age: "25", role: "ADMIN" }
// Object.freeze — immutable
const config = Object.freeze({
API_URL: "https://api.example.com",
MAX_RETRIES: 3
});
// config.API_URL = "new"; // ❌ silently fails (or throws in strict mode)
// Count properties
console.log(Object.keys(user).length); // 3
// Check if empty
const isEmpty = Object.keys({}).length === 0;
console.log(isEmpty); // trueTip
Tip
Use Object.entries() with destructuring in forEach for clean iteration: Object.entries(obj).forEach(([key, value]) => { }). This gives you both key and value in a readable format.
keys/values/entries return arrays for .map/.filter.
Common Mistake
Warning
Object.freeze() only freezes the top level (shallow freeze). Nested objects can still be modified: frozen.nested.prop = 'new' works! For deep freeze, recursively freeze all nested objects or use a library like Immutable.js.
Practice Task
Note
Object utilities: (1) Use Object.entries to convert a user object into an HTML table string. (2) Use Object.fromEntries to transform all values to uppercase. (3) Freeze a config object and verify modifications are silently ignored.
Quick Quiz
Key Takeaways
- Object.keys(obj) — Returns array of property names: ['name', 'age', 'email']
- Object.values(obj) — Returns array of values: ['Alice', 25, 'alice@email.com']
- Object.entries(obj) — Returns array of [key, value] pairs: [['name','Alice'], ['age',25]]