In this chapter, we are going to cover Object.keys, values, and entries. We have already spoken about methods such as map.keys(), map.values(), map.entries().
Similar methods are supported by plain objects, as well. Only the syntax differs a little.
Defining Object.keys, values, and entries
As a rule, for plain objects, you can use the methods below:
- For returning an array of key, the Object.keys(obj) method is used.
- For returning an array of values, the Object.values(obj) method is used.
- For returning an array of [key, value] pair, the Object.entries(obj) method is used.
There are significant differences compared to Map. Here we will cover them, as well.
The first distinction is that here we need to call Object.keys(obj) but not obj.keys().
So, having an object such as data, which can perform its own data.values() method. However, you may call Object.values(data) on that object, as well. Another essential difference is that Object.* methods may return real arrays, not iterabales.
Let’s consider the following example:
So, in the example above, we have the following:
- Object.keys(user) = ["name", "age"]
- Object.values(user) = ["Jack", 35]
- Object.entries(user) = [ ["name","Jack"], ["age",35] ]
For looping over property values, you can use Object.values like this:
In circumstances when you need symbols, you can use a separate method Object.getOwnPropertySymbols, returning an array that consists of only symbolic keys.
Transformation of Objects
Usually, objects don’t obtain the methods that arrays have (for instance, filter, map, and so on).
If you wish to use them, you can apply the Object.entries method, followed by Object.fromEntries.
Here is the sequence of actions:
- Apply Object.entries(obj) for getting an array of value/key pairs from obj.
- Apply array methods on the array.
- Apply Object.fromEntries(array) on the resulting array for turning it back to an object.
Here is an example:
This means allows making robust transformations.