Often, I end up with a list of objects and want to find some items on the list using a unique identifier. One example: enhancing other data that relates to an item on my list.
There are many ways to do this, but some are better than others, especially when there is a lot of data.
Let's see with a simple example:
const data = [{
id: 3,
name: "New Brunswick"
}, {
id: 8,
name: "Ontario"
}, {
id: 10,
name: "Quebec"
},
];
If we want to retrieve the name of the province identified by the id 10, how do we do it? 🤔
const province10 = `?`;
Let's see some solutions we could use! 🤗
Solution #0 - Using find
A simple solution could be to use the find function to retrieve the first element that satisfies our search:
const province10 = data.find(element => element.id === 10);
This works perfectly, but it may not be quick if you need to find a lot of items and/or multiple times. Let's see if we can do better. 😋

Solution #1 - Using reduce
What if we had the following data in our hands:
{
3: {id: 3, name: 'New Brunswick'},
8: {id: 8, name: 'Ontario'},
10: {id: 10, name: 'Quebec'},
}
Some people call this structure a dictionary or an index. If we had it, we could directly access the element we want using its identifier: dictionary[10]
. Wouldn't that be easier? 🤔
Let's see how we can create it using one of my favourite array functions: reduce! 🥰

const dictionary = data.reduce((dictionary, province) => {
dictionary[province.id] = province;
return dictionary;
}, {});
const province10 = dictionary[10];
// {id: 10, name: 'Quebec'}
The biggest advantage of this structure is that you only need to iterate on your array one time (to build the dictionary). If you have a lot of data, you should be able to get the element you want faster. 🤑
But, if you're not a fan of functional programming, I've another solution you could use. 😉
Solution #2 - Using object destructuring
While writing this post, I found another elegant solution that I like, but wouldn't use in a good codebase because it's more complex.
const dictionary = Object.assign({}, ...data.map((x) => ({[x.id]: x})));
Do you understand easily this one? Let me help you if not.
const dictionary = Object.assign({}, ...[
{8: {id:8,name:"Ontario"}},
{10: {id:10,name:"Quebec"}},
])
This solution use destructuring to create a dictionary with lots of smaller objects. All the generated objects are merged into a simpler one.
More complex, right? 😅

Conclusion
I hope this post introduced you to the concept of a JavaScript dictionary and that it helps you in the future! 🤗