I wanted to use a hashtable as set of some objects for a graphic libray, so that I can quickly remove these objects by saying something like set.remove(v2).
But it appears I cannot use these objects while I try to iterate the set, since the keys don’t have the right properties, even though a == shows that they are the same objects!
What can I do to iterate the set and use the properties or functions which are part of the keys?
Test case shown below, with rather unexpected results (for me)!
v1={'a':2,'b':3};
set={};
set[v1]=true;
// Access the object within set
var v2; for(var k in set) v2=k;
// At this moment, v2 and v1 should be the same object, but...
console.log(v2==v1); // returns true
console.log(JSON.stringify(v1)); // returns {"a":2,"b":3}
console.log(JSON.stringify(v2)); // returns "[object Object]" !!!
console.log(v1.a); // returns 2
console.log(v2.a); // causes error 'reference to undefined property v2.a' !!!
You’re trying to set an object as the key of another object, which isn’t possible in current ECMAScript implementations. When you call
set[v1]=true;, internally the engine convertsv1to a string, the result being"[object Object]"with no identifiable properties.ECMAScript 6 allows you to map objects to other values using
WeakMap, but the API is still in the early stages and currently only available in Chrome—with a command line switch—and Firefox.