Consider this scenario: SomeItem
represents the model for an object (which could be modeled as an interface in Typescript or as an imaginary item with the form of SomeItem
in untyped land).
Let's say we have a Set
:
mySet = new Set([{item: SomeItem, selected: true}, ...])
.
Now, suppose we want to determine whether itemA: SomeItem
is selected within the set.
What would be the most efficient way to accomplish this task?
The following attempts did not yield the desired result:
const isSelected = mySet.has({item: itemA, selected: true});
And neither did this:
const isSelected = Array.from(mySet).includes({item: itemA, selected: true});
This lack of success can be attributed to the fact that these approaches attempt to compare objects by reference rather than by value.
However, the following method does provide the expected outcome:
let isSelected: boolean;
mySet.forEach(state => {
if (state.item === itemA) {
isSelected = state.selected;
}
});
Despite its effectiveness, I can't help but feel that there may be a more appropriate solution.
Therefore, How can I retrieve the value of a specific property from an object within a Set?