A javascript WeakMap ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap ) does not allow you to get the key, or the length or size, by design.
Is it possible to nevertheless loop over entries in some way ?
If not .. how does the Chrome console do this ?
Is it possible to nevertheless loop over entries in some way?
No, as you say, the contents of a WeakMap
are not accessible by design, and there is no iterability.
If not … how does the Chrome console do this?
The console uses the debugging API of the JS engine, which allows access to the internals of objects (also to promise states, wrapped primitives, etc.) and many more.
You can use this small snippet for universal forEach. However it uses lodash and can be enhanced greatly.
import lodashForEach from 'lodash/forEach'; import entries from 'lodash/entries'; /** * @since lodash@4.17.3 * @param {Array|Map|Object|Set|WeakMap|WeakSet} iterable * @param {Function} iteratee * @example * const iterable = new Map(); * iterable.set('somekey1', 1); * iterable.set('somekey2', 2); * // or * const iterable = new Set(); * iterable.add("entry1"); * iterable.add("entry2"); * // run function * forEach(iterable, (value, key) => { * console.group('-'); * console.info('KEY'); * console.log(key); * console.info('VALUE'); * console.log(value); * console.groupEnd(); * }); */ function forEach(iterable, iteratee) { lodashForEach((iterable instanceof Set || iterable instanceof WeakSet) ? Array.from(iterable) : entries(iterable), (entry, index, collection) => { iteratee(entry[1], entry[0], collection, index); }); return iterable; } export default forEach;
UPDATE
After long time passed I found this answer incorrect. The thing is older version of core-js polyfill library has fixed bug where it replaces native WeakMap implementation with its own. So my solution is not valid in modern browsers.
function forEach(iterable, iteratee) { switch (true) { case Array.isArray(iterable) || iterable instanceof Map: iterable.forEach(iteratee); break; case iterable instanceof Set: Array.from(iterable).forEach(iteratee); break; case iterable instanceof WeakMap || iterable instanceof WeakSet: // some kind of warning break; default: Object.keys(iterable).forEach((key) => iteratee.call(null, iterable[key], key)); break; } return iterable; }