Sometimes, we want to map object property values of an object to new values instead of mapping array values.
In this article, we’ll look at how to use JavaScript array’s map
method with object instead of arrays.
Object.keys
The object.keys
method returns an array of a JavaScript object’s string keys.
Therefore, we can loop through the keys to map the property values to their new values.
For instance, we can write:
const obj = {
a: 1,
b: 2,
c: 3
};
for (const key of Object.keys(obj)) {
obj[key] *= 2
}
console.log(obj)
We have the obj
object that has 3 properties in it.
Then we use Object.keys
with obj
to return the keys.
And then we use the for-of loop to loop through the keys.
Then we can use that to do what we want.
In this example, we multiple each property value by 2.
Therefore, obj
is now:
{a: 2, b: 4, c: 6}
Object.keys and reduce
We can also combine the Object.keys
method with the reduce
method to map the values of properties if an object to new values.
For instance, we can write:
const obj = {
a: 1,
b: 2,
c: 3
};
const newObj = Object.keys(obj).reduce((result, key) => {
result[key] = obj[key] * 2
return result
}, {})
console.log(newObj)
We call reduce
on the string keys array returned by Object.keys
.
The reduce
callback has the result
object which is the object that we have so far.
key
has the string key value.
Then we get result[key]
with the value we want.
We get the obj[key]
value and multiply it by 2.
Then we return the result
value.
The 2nd argument is set to an object so that the initial value of result
is an object.
This way, we can put property values in them.
Therefore, newObj
has the same value as the previous example.
Object.fromEntries and Object.entries
We can use the Object.fromEntries
method to create an object from an array of arrays of key-value pairs.
And we can use Object.entries
to return an array of arrays of key-value pairs of an object.
For example, we can write:
const obj = {
a: 1,
b: 2,
c: 3
};
const newObj = Object.fromEntries(
Object.entries(obj).map(
([key, value]) => ([key, value * 2])
)
)
console.log(newObj)
We call Object.entries
with obj
to get the key-value pairs in an array.
Then we call map
with a callback that destructures the key-value pairs.
And we return an array of key-value pairs.
We changed the value by multiplying it by 2.
Then we use Object.fromEntries
to create an object from the new array of key-value pairs.
Therefore newObj
is:
{a: 2, b: 4, c: 6}
as we have before.
Conclusion
We can map object properties to new values by using some handy object methods that are available in JavaScript’s standard library.