To detect all the property values of object without knowing the key can be done in a number of ways depending on browsers. The majority of browsers support ECMAScript 5 (ES5). Let’s see what methods can be used for getting the property value based on different specifications.
You can use the methods below in the browsers supporting ECMAScript 5+. These methods detect values from an object and avoid enumerating over the prototype chain:
To make the code more compact, use the forEach:
The following method builds an array which contains object values:
To make those using Object.keys safe against null, then you can 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:
Object.getOwnPropertyNames instead of Object.keys.
ECMAScript 2015+ ( ES6)
It is easier to iterate Arrays with ECMAScript 2015. You can use the following script when working with values one-by-one in a loop:
To use ECMAScript 2015 fat-arrow functions and to map the object to an Array of values can become a one-liner code:
The ECMAScript 2015 specification introduces Symbol, instances of which can be used as property names. You can use the 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.
This just adds a method to object. Using fat-arrow functions can be a one-liner:
If you do not want to use shimming when a native Object.values exists, then you can run:
This specification adds Object.values and Object.entries where both return arrays. Object.values can be used with a for-of loop:
If you want to use both the key and the value, then you can use the Object.entries:
Object.keys/values/entries methods have similarity with for..in loop. They all ignore properties that apply Symbol(...) as a key. When you need symbols, you can use a separate method Object.getOwnPropertySymbols which returns an array consisting of only symbolic keys.