Episode 1 — Fundamentals / 1.24 — Object Methods
1.24.h — Object.values()
In one sentence:
Object.values(obj)returns an array of an object's own enumerable string-keyed property values, perfect for aggregation, searching, and data extraction.
Navigation: <- 1.24.g — Object.seal . 1.24 Exercise Questions ->
1. What does Object.values() do?
It returns a flat array of all the own, enumerable, string-keyed property values of an object.
const user = { name: "Alice", age: 30, role: "admin" };
const values = Object.values(user);
console.log(values); // ["Alice", 30, "admin"]
2. Syntax
Object.values(obj)
| Parameter | Description |
|---|---|
obj | The object whose own enumerable string-keyed property values are returned |
| Returns | any[] — an array of property values |
If obj is not an object, it is coerced:
Object.values("hi"); // ["h", "i"]
Object.values(42); // []
Object.values(true); // []
3. Same order as Object.keys()
Object.values() returns values in the same order as Object.keys():
- Integer-like keys first (sorted ascending)
- String keys in insertion order
const obj = { b: 2, 10: "ten", a: 1, 2: "two", 1: "one" };
console.log(Object.keys(obj)); // ["1", "2", "10", "b", "a"]
console.log(Object.values(obj)); // ["one", "two", "ten", 2, 1]
// Same order — values correspond to keys positionally
4. Only own, enumerable, string-keyed properties
Same rules as Object.keys() and Object.entries():
const parent = { inherited: "yes" };
const child = Object.create(parent);
child.own = "mine";
Object.defineProperty(child, "hidden", {
value: "secret",
enumerable: false,
});
child[Symbol("id")] = 42;
console.log(Object.values(child)); // ["mine"]
// inherited, non-enumerable, and Symbol-keyed values excluded
5. Common patterns
Summing numeric values
const sales = { jan: 1200, feb: 980, mar: 1450, apr: 1100 };
const total = Object.values(sales).reduce((sum, val) => sum + val, 0);
console.log(total); // 4730
Finding maximum and minimum
const scores = { alice: 95, bob: 72, charlie: 88, diana: 91 };
const highest = Math.max(...Object.values(scores));
const lowest = Math.min(...Object.values(scores));
console.log(highest); // 95
console.log(lowest); // 72
Calculating average
const grades = { math: 90, science: 85, english: 92, history: 78 };
const vals = Object.values(grades);
const average = vals.reduce((sum, v) => sum + v, 0) / vals.length;
console.log(average); // 86.25
Checking if a value exists
const colors = { primary: "blue", secondary: "gray", accent: "orange" };
console.log(Object.values(colors).includes("blue")); // true
console.log(Object.values(colors).includes("red")); // false
Finding the key for a given value (reverse lookup)
const statusCodes = { OK: 200, NOT_FOUND: 404, ERROR: 500 };
function findKeyByValue(obj, targetValue) {
return Object.keys(obj).find(key => obj[key] === targetValue);
}
console.log(findKeyByValue(statusCodes, 404)); // "NOT_FOUND"
console.log(findKeyByValue(statusCodes, 200)); // "OK"
6. Converting to a Set for unique values
const roles = { alice: "admin", bob: "user", charlie: "admin", diana: "moderator" };
const uniqueRoles = new Set(Object.values(roles));
console.log(uniqueRoles); // Set {"admin", "user", "moderator"}
console.log(uniqueRoles.size); // 3
Counting unique values
function countUniqueValues(obj) {
return new Set(Object.values(obj)).size;
}
console.log(countUniqueValues({ a: 1, b: 2, c: 1, d: 3, e: 2 })); // 3
7. Combined usage with keys and entries
The three methods complement each other:
const inventory = { apples: 5, bananas: 12, cherries: 0, dates: 8 };
// Object.keys — property names
const items = Object.keys(inventory);
// ["apples", "bananas", "cherries", "dates"]
// Object.values — just the quantities
const quantities = Object.values(inventory);
// [5, 12, 0, 8]
// Object.entries — both together
const pairs = Object.entries(inventory);
// [["apples", 5], ["bananas", 12], ["cherries", 0], ["dates", 8]]
Choosing the right method
| You need | Use |
|---|---|
| Only property names (to validate shape, list fields) | Object.keys() |
| Only values (to sum, find max, check existence) | Object.values() |
| Both key and value (to iterate, transform, filter) | Object.entries() |
8. Real-world examples
Summing a shopping cart
const cart = {
"Laptop": 999,
"Mouse": 29,
"Keyboard": 79,
"Monitor": 349,
};
const total = Object.values(cart).reduce((sum, price) => sum + price, 0);
console.log(`Total: $${total}`); // "Total: $1456"
Data extraction from API response
const apiResponse = {
user1: { name: "Alice", score: 95 },
user2: { name: "Bob", score: 72 },
user3: { name: "Charlie", score: 88 },
};
// Extract all user objects into an array
const users = Object.values(apiResponse);
console.log(users);
// [
// { name: "Alice", score: 95 },
// { name: "Bob", score: 72 },
// { name: "Charlie", score: 88 }
// ]
// Now use standard array methods
const names = users.map(u => u.name);
console.log(names); // ["Alice", "Bob", "Charlie"]
const topScorers = users.filter(u => u.score >= 85);
console.log(topScorers);
// [{ name: "Alice", score: 95 }, { name: "Charlie", score: 88 }]
Flattening nested config values
const envConfig = {
DB_HOST: "localhost",
DB_PORT: "5432",
API_KEY: "abc123",
DEBUG: "true",
};
// Check if any config value is empty
const hasEmpty = Object.values(envConfig).some(v => v === "" || v === undefined);
console.log(hasEmpty); // false
// Find which values look like numbers
const numericValues = Object.values(envConfig).filter(v => !isNaN(Number(v)));
console.log(numericValues); // ["5432"]
Counting value frequencies
const survey = { q1: "yes", q2: "no", q3: "yes", q4: "yes", q5: "no", q6: "maybe" };
const frequency = Object.values(survey).reduce((acc, answer) => {
acc[answer] = (acc[answer] || 0) + 1;
return acc;
}, {});
console.log(frequency);
// { yes: 3, no: 2, maybe: 1 }
Checking if all values pass a condition
const permissions = { read: true, write: true, delete: false, admin: false };
const allGranted = Object.values(permissions).every(v => v === true);
console.log(allGranted); // false
const anyGranted = Object.values(permissions).some(v => v === true);
console.log(anyGranted); // true
Converting object to display list
const userProfile = {
"Full Name": "Alice Johnson",
"Email": "alice@example.com",
"Location": "New York",
"Member Since": "2023",
};
const displayLines = Object.values(userProfile).join(" | ");
console.log(displayLines);
// "Alice Johnson | alice@example.com | New York | 2023"
9. Object.values with arrays
Since arrays are objects, Object.values works on them (though it is redundant):
const arr = ["a", "b", "c"];
console.log(Object.values(arr)); // ["a", "b", "c"]
// Same as [...arr] — Object.values is not needed for arrays
10. Edge cases
// Empty object
Object.values({}); // []
// null / undefined — throws TypeError
// Object.values(null); // TypeError!
// Object.values(undefined); // TypeError!
// String (character values)
Object.values("abc"); // ["a", "b", "c"]
// Array with holes (sparse array)
Object.values([1, , 3]); // [1, undefined, 3]
// Object with numeric keys (sorted)
Object.values({ 2: "b", 1: "a", 3: "c" }); // ["a", "b", "c"]
11. Performance note
Like Object.keys(), Object.values() creates a new array on each call. Cache the result when used multiple times:
// Good
const vals = Object.values(largeObj);
const sum = vals.reduce((a, b) => a + b, 0);
const avg = sum / vals.length;
// Wasteful — creates the array twice
const sum2 = Object.values(largeObj).reduce((a, b) => a + b, 0);
const avg2 = sum2 / Object.values(largeObj).length;
Key takeaways
Object.values(obj)returns an array of own enumerable string-keyed property values.- Values are in the same order as
Object.keys(): integer keys sorted first, then string keys by insertion order. - Great for aggregation:
reducefor sums,Math.maxfor maximums,every/somefor checks. - Use
includesfor value existence checks; combine withObject.keysfor reverse lookups. - Convert to
Setfor unique value extraction. - Choose
valueswhen you need only the data,keysfor names,entriesfor both.
Explain-It Challenge
Explain without notes:
- What does
Object.values({ x: 10, y: 20, z: 30 })return? - How would you sum all numeric values in an object using
Object.values? - If you need both the key and value during iteration, should you use
Object.valuesorObject.entries? Why?
Navigation: <- 1.24.g — Object.seal . 1.24 Exercise Questions ->