Can your language do this?
When doing various kinds of data processing with arrays and lists, it's a common practice to build up a lookup table based on an ID in the list for optimizations. In Go, you can do this by initiating a map and then looping over the items.
In go we can do this doing something like this:
users := []User{
{ID: 1, Name: "Alice", Email: "alice@example.com"},
{ID: 2, Name: "Bob", Email: "bob@example.com"},
{ID: 3, Name: "Charlie", Email: "charlie@example.com"},
}
userMap := make(map[int]User)
for _, user := range users {
userMap[user.ID] = user
}
We can create a similar pattern in Javascript.
const users = [
{ id: 1, name: "Alice", email: "alice@example.com" },
{ id: 2, name: "Bob", email: "bob@example.com" },
{ id: 3, name: "Charlie", email: "charlie@example.com" },
];
const userMap = {};
for (const user of users) {
userMap[user.id] = user;
}
If we want a more functional way of performing the same operation, we can do this with a reduce.
const userMap = users.reduce((map, user) => {
map[user.id] = user;
return map;
}, {});
Reduce is nice, but sometimes I forget to return the accumulator, and this can be a source of some frustration. Object data type offers a number of builtin static methods which are useful for manipulating various objects in Javascript. One static method, fromEntries, affords us the following approach:
const userMap = Object.fromEntries(
users.map(user => [user.id, user])
);
This is a nice, sleek, and more straightforward approach to take a list and create a key-value object. Object offers has the correlariy method: toEntries
. Not only can we transform an array into an object, but we can also use toEntries to transform objects. For example:
const object2 = Object.fromEntries(
Object.entries(object1).map(([key, val]) => [key, val / 10]),
);