1

I have a WeakMap like this:

let obj = new WeakMap();
let objKey1={"a":1};
let objKey2={"b":2};
let objKey3={"c":3};

obj.set(objKey1,"value1");
obj.set(objKey2,"value2");
obj.set(objKey3,"value3");

Is there a way to get the length / number of keys stored in obj?

I tried Object.keys(obj).length but it returns 0

cak3_lover
  • 1,440
  • 5
  • 26
  • 2
    You cannot. However, that might be [an XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). The reason you're not allowed is that the length can change, once GC runs. There is little value of looking at that value. Usually *either* you need a WeakMap *or* a normal map where you can get the size of it. – VLAZ May 26 '22 at 09:26
  • 1
    You can see this https://stackoverflow.com/questions/32402837/how-to-iterate-over-a-weakmap – mohamed chadad May 26 '22 at 09:45

1 Answers1

3

From the documentation

But because a WeakMap doesn't allow observing the liveness of its keys, its keys are not enumerable. There is no method to obtain a list of the keys.

It should therefore follow that there is no way to get the number of keys either.

shree.pat18
  • 21,449
  • 3
  • 43
  • 63