简体   繁体   中英

Extract value of property from object in a Set?

For the example, SomeItem is the model for an object (would be modeled as an interface in Typescript or you can just imagine that there is an item with the form of SomeItem if we are in untyped land.

Say I have a Set : mySet = new Set([{item: SomeItem, selected: true}, ...]) .

And I want to check if itemA: SomeItem is selected or not.

What is the cleanest way to do this?

This did not work:

const isSelected = mySet.has({item: itemA, selected: true});

Nor did this:

const isSelected = Array.from(mySet).includes({item: itemA, selected: true});

I'm assuming the above two did not work because it is trying to compare the objects by reference, rather than value.

This does work:

let isSelected: boolean;
mySet.forEach(state => {
  if (state.item === itemA) {
    isSelected = state.selected;
  }
});

But my gut tells me there is a correct way to do this.

So, How do I extract the value of a property of an object in a Set?

Comparing two objects with the same properties returns true only if they have the same reference, I would suggest to compare their properties as the properties are primitive values..

The array some method can be used to filter if the set contains an specific object

 let mySet = new Set([{item: 'SomeItem', selected: true}]); let itemA = "SomeItem"; let isSelected = Array.from(mySet).some(element => element.item === itemA); console.log(isSelected); 

Let's take a look at it this way, Set s mainly return an iterable. Sure, they're hashed in order, as is a Map , but from the looks of your data structure, a Map would benefit you more here.

const x = new Set([
    { "foo": 1, selected: true },
    { "bar": 1, selected: false },
    { "baz": 1, selected: false },
    { "barf": 1, selected: false },
]);

Now, to get what you're looking for, you'll need as you did, convert to an array using Array.from (or [...x] spread it) and iterate, finding they key.

Now, as a Map:

const y = new Map();
y.set("foo", { selected: true });
y.set("bar", { selected: false });
y.set("baz", { selected: false });
y.set("barf", { selected: false });

With this, you simply change the structure slightly to give item1 or whatever you use the Map key, and set whatever elements you want.

y.has("foo"); // true
y.get("foo").selected; //true

So if you wanted here, it's much easier to grab the iterable key name and get which Map index has the property you want

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM