JavaScript provides three essential methods to extract data from objects in different formats:
Object.keys(obj)– Returns an array of the object’s own enumerable property names (keys).Object.values(obj)– Returns an array of the object’s own enumerable property values.Object.entries(obj)– Returns an array of [key, value] pairs from the object.
Summary of Object Methods
| Method | Returns |
|---|---|
Object.keys(obj) | Array of keys (strings) |
Object.values(obj) | Array of values |
Object.entries(obj) | Array of [key, value] pairs (arrays) |
📌 Deep Dive: Extracting Keys, Values, and Entries
JAVASCRIPT
const user = {
name: "Alice",
age: 25,
active: true
};
console.log(Object.keys(user)); // ["name", "age", "active"]
console.log(Object.values(user)); // ["Alice", 25, true]
console.log(Object.entries(user)); // [["name", "Alice"], ["age", 25], ["active", true]]
Output
["name", "age", "active"]["Alice", 25, true]
[["name", "Alice"], ["age", 25], ["active", true]]
These methods are very useful for:
- Iterating over object properties using loops (e.g.,
for...oforforEach). - Transforming objects into arrays for data manipulation.
- Converting objects to other formats, like Maps or JSON.
📌 Deep Dive: Looping Through Object with Object.entries()
JAVASCRIPT
const scores = { alice: 80, bob: 90, charlie: 70 };
for (const [name, score] of Object.entries(scores)) {
console.log(`${name} scored ${score}`);
}
Output
alice scored 80bob scored 90
charlie scored 70

💡 Remember:
These methods only include the object’s own enumerable properties; inherited or non-enumerable properties are excluded.
⚠️ Important:
The order of keys, values, and entries is the same and corresponds to the order of the properties in the object, which generally follows creation order for string keys.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
Which method returns an array of arrays, each containing a key and its corresponding value?
Question 2 of 2
What do Object.keys() and Object.values() return, respectively?
0/2
Loading results...