How to Convert Array of Objects to Hash Map By Key in JavaScript
How can we convert an array of objects to a hash map, where each key is a property of each object?
Suppose we have an array of objects.
const objs = [
{ id: 0, name: "Bob", age: 10 },
{ id: 1, name: "John", age: 12 },
{ id: 2, name: "Alice", age: 14 },
];
Let’s say we want to convert this array into a hashmap, where each object is indexed by its id
.
const objsById = {
0: { id: 0, name: "Bob", age: 10 },
1: { id: 1, name: "John", age: 12 },
2: { id: 2, name: "Alice", age: 14 },
}
Convert array of objects to hash map using reduce()
const objsById = objs.reduce((map, obj) => {
map[obj.id] = obj;
return map;
}, {});
objsById[0] // { id: 0, name: "Bob", age: 10 }
If we want a simple one-liner, we can take some syntactical shortcuts.
const objsById = objs.reduce((map, obj) => ((map[obj.id] = obj), map), {});
objsById[0] // { id: 0, name: "Bob", age: 10 }
If we’re using TypeScript, we’ll want to add a type definition to the avoid the “Property does not exist” error.
Let’s say we have a User
interface for the objects in our array.
const objsById: { [key: number]: User } = ...;
Convert array of objects to hash map using map()
We can achieve the same functionality using map()
.
const objsById = new Map(objs.map(obj => [obj.id, obj]));
In order to get a value by the key, we’ll have to use get()
.
objsById.get(0) // { id: 0, name: "Bob", age: 10 }
objsById[0] // undefined
If we’re using TypeScript, we can add types to the Map
.
const objsById = new Map<number, User>(objs.map(obj => [obj.id, obj]));
Note that we can map any property to any other property in our object. This means we can map from
id
toname
or fromname
toage
.