Sometimes, we may want to convert a JavaScript objects array into a hash map object with the key of each entry being a property value of the object.
In this article, we’ll look at how to convert a JavaScript object array into a hash map object.
Array.prototype.reduce
The JavaScript array’s reduce
method lets us convert an object array into an object easily.
For instance, we can write:
const arr = [{
key: 'foo',
val: 'bar'
},
{
key: 'hello',
val: 'world'
}
];
const result = arr.reduce((map, obj) => {
map[obj.key] = obj.val;
return map;
}, {});
console.log(result)
to do the conversion.
We have an arr
object array.
We call reduce
to combine the objects in the array, which is obj
into the object we return, which is map
.
We get the obj.key
and set the as a property name of map
.
And we use obj.val
as the value of obj.key
.
The 2nd argument is an empty object, which is the initial value of the reduced result.
As a result, the value of result
is:
{foo: "bar", hello: "world"}
Convert the Object Array to a Hash Map with the Map Constructor
We can convert the object array to a hash map with the Map
constructor.
For instance, we can write:
const arr = [{
key: 'foo',
val: 'bar'
},
{
key: 'hello',
val: 'world'
}
];
const result = new Map(arr.map(({
key,
val
}) => ([
key,
val
])));
console.log(result)
In the map
method, we destructure the key
and val
properties from the parameter object in the callback.
Then we return an array with the key
and val
inside.
We then pass that to the Map
constructor to create a hash map object from it.
And so, result
is:
Map(2) {"foo" => "bar", "hello" => "world"}
according to the console log.
Lodash keyBy Method
We can also use the Lodash keyBy
method to create the same object in the first example.
For instance, we can write:
const arr = [{
key: 'foo',
val: 'bar'
},
{
key: 'hello',
val: 'world'
}
];
const result = _.keyBy(arr, o => o.key);
console.log(result)
We just pass in a callback to return the properties that the returned object will have.
The entries of arr
will be set as the value of the keys according to the value of the key
property.
And so we get:
{
"foo": {
"key": "foo",
"val": "bar"
},
"hello": {
"key": "hello",
"val": "world"
}
}
as the value of result
.
Object.fromEntries
Another way to create a JavaScript object from an object array is to use the Object.fromEntries
method.
For instance, we can write:
const arr = [{
key: 'foo',
val: 'bar'
},
{
key: 'hello',
val: 'world'
}
];
const result = Object.fromEntries(
arr.map(({
key,
val
}) => ([
key,
val
]))
)
console.log(result)
We pass in an array of key-value pair arrays as we did when we try to create a Map
instance from the array.
And so we get the same result as the first example for the value of result
.
Conclusion
We can use array and object methods that are part of the JavaScript standard library of Lodash to create JavaScript object arrays to objects.