I often find myself passing around objects that have IDs or names that identify them but are also a property of the object. For example:
type ExampleItemName = string;
interface ExampleItem {
name: ExampleItemName ;
value: number;
}
I also often need to create lists of these items, and I find it's convenient to be able to access the items by their name
s. The most logical data structure I see for this is a Map
, ie:
type ExampleItemList = Map<ExampleItemName, ExampleItem>;
This is handy and convenient, as I can access any item by its name
with Map.get
but I can also easily iterate through the whole list using for...of
.
However, this feels wrong to me because the name
information is duplicated - it is present both in the key and the value of the map. If the name
of an ExampleItem
changes, the corresponding key in the map doesn't, so it feels fragile.
Is this a bad practice? If so, what's a better way to achieve the functionality I am looking for?