The JavaScript Object.values() method
The Object.values() method returns an array of an object's own property values. Object.values({a: 1, b: 2}) gives [1, 2]. With the values in an array, you can sum, filter or transform them using methods like reduce() — handy when you care about the data, not the keys.
Overview
Object.values() is the values-only counterpart to Object.keys(): it gives you an array of the object's values, ignoring the keys. When you have an object acting as a lookup or a record and you want to do math or filtering on the values, this is the shortcut.
Total up an object of prices with Object.values(prices).reduce((a, b) => a + b, 0). Find the largest with Math.max() and a spread. Check if any value matches a condition with some(). The values come back in the same insertion order as the keys would.
It rounds out the trio with Object.keys() and Object.entries(). Use keys() when you need the names, values() when you need the data, and entries() when you need both at once.
Syntax
const values = Object.values(obj)
Object.values({ a: 1, b: 2 }) // [1, 2]
Parameters
The Object.values() method accepts the following parameters.
| Parameter | Description |
|---|---|
obj |
The object whose own enumerable property values you want as an array. |
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const cart = { book: 12, pen: 3, lamp: 25 };
const total = Object.values(cart).reduce((sum, n) => sum + n, 0);
document.getElementById('out').textContent = 'Total: $' + total; // Total: $40
</script>
Best practices
- Sum object values with
Object.values(obj).reduce((a, b) => a + b, 0). - Use it when you only care about the data; use Object.keys() when you need the names.
- Combine with Math.max() and a spread to find the largest value.
- Values come back in insertion order, matching what the keys would give.
Frequently asked questions
What does Object.values() return?
How do I sum the values of an object?
Object.values(obj).reduce((total, n) => total + n, 0).What is the difference between Object.values() and Object.keys()?
Object.values() returns the values; Object.keys() returns the property names.How do I get the highest value in an object?
Math.max(...Object.values(obj)).