I am playing with ECMAScript 6 symbols and maps in Node.JS v0.11.4 with the --harmony
flag. Consider the following.
var a = Map();
a.set(Symbol(), 'Noise');
// Prints "1"
console.log(a.size);
Can the value 'Noise'
be retrieved given the property is identified by an "anonymous" symbol key, which is guaranteed to be unique?
For getting all of the keys of an Object you can use Object. keys() . Object. keys() takes an object as an argument and returns an array of all the keys.
To get all own properties of an object in JavaScript, you can use the Object. getOwnPropertyNames() method. This method returns an array containing all the names of the enumerable and non-enumerable own properties found directly on the object passed in as an argument.
It is not possible to do it in node.js because the current version of v8 hasn't implemented iteration as indicated in this bug report.
We can confirm that by looking at the source code of v8's collection.js:
InstallFunctions($Map.prototype, DONT_ENUM, $Array(
"get", MapGet,
"set", MapSet,
"has", MapHas,
"delete", MapDelete,
"clear", MapClear
));
But, as can be seen in ECMAScript 6 wiki, there should also be items()
, keys()
, and values()
. v8 probably didn't implement these methods before, because it didn't support generators. But now it does since May of this year. It should be a just a matter of time until this is implemented.
If you need to have this functionality now, you can use map-set-for-each which polyfills forEach
. You will need to modify it to add case 'symbol':
after case 'object':
.
a.forEach(function(value, key) {
if (value === 'Noise') {
console.log('Give mak the bounty');
}
});
When v8 implements iteration of Map
you will be able to find Noise
like this:
for (let [key, value] of a) {
if (value === 'Noise') {
console.log('Upvotes for future');
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With