Appearance
How to Get All Property Values of a JavaScript Object
Getting all property values of an object without knowing the keys can be done in several ways. Modern environments universally support ECMAScript 5 (ES5). Let’s see what methods can be used for getting property values based on different specifications.
ECMAScript 5+
You can use the methods below in browsers supporting ECMAScript 5+. These methods detect values from an object and avoid enumerating over the prototype chain:
Get values using a for loop
Output appears here after Run.
To make the code more compact, use the forEach:
Get values using forEach
Output appears here after Run.
The following method builds an array which contains object values:
Build an array with map
Output appears here after Run.
To make those using Object.keys safe against null, you can run:
Handle null safely
Output appears here after Run.
Object.keys returns enumerable properties. Using Object.keys is usually effective for iterating over simple objects. If you have something with non-enumerable properties to work with, you can use:
Get all own property names
Output appears here after Run.
ECMAScript 2015+ (ES6)
Iterating over arrays is more straightforward with ECMAScript 2015. You can use the following script when working with values one-by-one in a loop:
Iterate values one-by-one
Output appears here after Run.
To use ECMAScript 2015 fat-arrow functions and map the object to an array of values, you can write a one-liner:
Map to an array of values
Output appears here after Run.
The ECMAScript 2015 specification introduces Symbol, instances of which can be used as property names. You can use Object.getOwnPropertySymbols to get the symbols of an object to enumerate over. The new Reflect API from ECMAScript 2015 provides Reflect.ownKeys, returning a list of property names and symbols.
Object.values
This adds a method to the Object constructor. Using fat-arrow functions can make it a one-liner:
Polyfill Object.values
Output appears here after Run.
If you do not want to overwrite a native Object.values when it exists, you can run:
Safe polyfill for Object.values
Output appears here after Run.
ECMAScript 2017+
This specification adds Object.values and Object.entries where both return arrays. Object.values can be used with a for...of loop:
Use native Object.values
Output appears here after Run.
If you want to use both the key and the value, then you can use Object.entries:
Use Object.entries
Output appears here after Run.
The Object.keys, Object.values, and Object.entries methods are similar to the for...in loop in that they only iterate over enumerable string-keyed properties. They ignore properties that use Symbol(...) as a key. When you need symbols, you can use the separate method Object.getOwnPropertySymbols, which returns an array consisting of only symbolic keys.