2

In JavaScript, I try the following:

let set1 = new Set([1]);
let set2 = new Set([2]);
let obj = {};
console.log("obj[set2] gives: ", obj[set2]);
obj[set1] = "Should be set1";

console.log(obj);
console.log("obj[set2] gives: ", obj[set2]);

It appears, that instead of treating the Set object as a key, it uses the string "[object Set]" as the key, thus making all Sets identical if used as keys. Why is this the correct behavior? Is there a way to use a Set as the key of an object, so I can look up a value associated with a particular Set? Thanks!

2 Answers 2

2

Object keys can only be strings (or Symbols, rarely). If you try to assign a key which is not a string, it will be cast to a string before being put onto the object.

See what happens when you try to turn a Set into a string:

let set1 = new Set([1]);
let set2 = new Set([2]);
console.log(
  String(set1),
  String(set2)
);

No matter what the set contains, when cast to a string, you get [object Set]. So, as expected:

obj[set1]           ===  obj[set2]
obj['[object Set]'] ===  obj['[object Set]']

If you want to use non-string keys, you should use a Map, whose "keys" can be any value at all, and not just strings:

let set1 = new Set([1]);
let set2 = new Set([2]);
const map = new Map();
console.log("obj[set2] gives: ", map.get(set2));
map.set(set1, "Should be set1");
console.log("obj[set2] gives: ", map.get(set2));

Sign up to request clarification or add additional context in comments.

2 Comments

Using the Map object no longer works- it now uses the === comparison operator which checks if objects themselves are equal. Running the code snippet outputs "obj[set2] gives: undefined" now. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
I don't think the behavior has changed. The problem OP was having initially is that the last log was producing an output rather than undefined. The last snippet in my answer is an illustration of how one can get the last log to output undefined (rather than the value for set1, which was undesirable when not doing .get(set1))
0

This is because obj[set1] = "Should be set1"; is really saying obj['undefined'] = 'Should be set1';, then you are testing for another obj[set2] where set2 is undefined (again cast to a String), so you get 'Should be set1'. If you want to know if a set has something it's setWhatever.has(value);.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.