How to Get All Keys and Values of Object in JavaScript
JavaScript provides three convenient methods for working with objects:
| Method | Description | Returns |
|---|---|---|
Object.keys() | Get all keys of object | string[] |
Object.values() | Get all values of object | any[] |
Object.entries() | Get all pairs | [key, value][] |
Get All Keys
const user = { name: "Alice", age: 25, role: "admin" };
const keys = Object.keys(user);
console.log(keys); // ["name", "age", "role"]
Get All Values
const values = Object.values(user);
console.log(values); // ["Alice", 25, "admin"]
Get Key-Value Pairs
const entries = Object.entries(user);
console.log(entries);
// [["name", "Alice"], ["age", 25], ["role", "admin"]]
Iterating Over Object
Using for...of and Object.entries():
for (const [key, value] of Object.entries(user)) {
console.log(`${key}: ${value}`);
}
Using for...in (less recommended):
for (const key in user) {
if (user.hasOwnProperty(key)) {
console.log(`${key}: ${user[key]}`);
}
}
for...inenumerates all enumerable properties, including inherited ones. So you need to usehasOwnProperty.
Important:
Order of keys in object is not strictly guaranteed (but in practice — stable in modern browsers).
Summary
Object.keys()— get keysObject.values()— get valuesObject.entries()— get key-value pairs
These are basic methods for everyday work with objects in JavaScript.