Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the value of a Symbol property

I have an object in NodeJS (a socket to be accurate).

When I print it, I see that one of the entries is this:

[Symbol(asyncId)]: 2781 // the numeric value changes

How can I obtain the value of such key?

I've tried socket['[Symbol(asyncId)]'] but got undefined.

The expression socket.[Symbol(asyncId)] would obviously not work.

like image 409
goodvibration Avatar asked Mar 06 '23 04:03

goodvibration


2 Answers

You will not be able to access it directly by key, unless you have a reference to the actual: Symbol('asyncId'), because every Symbol is unique

The Symbol() function returns a value of type symbol, has static properties that expose several members of built-in objects, has static methods that expose the global symbol registry, and resembles a built-in object class but is incomplete as a constructor because it does not support the syntax "new Symbol()".

What you can do is loop through the object's own property keys, using Reflect.ownKeys, which will include normal properties & symbols, and then obtain that reference.

You can also use: Object.getOwnPropertySymbols()

function getObject() {
   // You don't have access to this symbol, outside of this scope.
  const symbol = Symbol('asyncId');

  return {
    foo: 'bar',
    [symbol]: 42
  };

}

const obj = getObject();

console.log(obj);
console.log(obj[Symbol('asyncId')]); // undefined

// or Object.getOwnPropertySymbols(obj)
const symbolKey = Reflect.ownKeys(obj)
  .find(key => key.toString() === 'Symbol(asyncId)')
  
console.log(obj[symbolKey]); // 42
 

NOTE: The object can have multiple keys where key.toString() === 'Symbol(asyncId)', this won't be usual, but be aware, so you may want to use other function other than .find if that's the case.

NOTE II: You should not change the value of that property, since it's supposed to be for internal access only, even if the property is not read only.

function getObject() {
       // You don't have access to this symbol, outside of this scope.
      const symbol = Symbol('asyncId');
      const symbol2 = Symbol('asyncId');

      return {
        foo: 'bar',
        [symbol]: 'the value I don\'t want',
        [symbol2]: 'the value I want'
      };

}
const obj = getObject();

const symbolKey = Reflect.ownKeys(obj)
  .find(key => key.toString() === 'Symbol(asyncId)')
  
console.log(obj[symbolKey]); // the value I don't want

console.log('=== All values ===');
Reflect.ownKeys(obj)
  .forEach(key => console.log(obj[key]));
like image 117
Marcos Casagrande Avatar answered Mar 15 '23 23:03

Marcos Casagrande


Use Object.getOwnPropertySymbols(obj) and iterate over it

like image 32
aciurea Avatar answered Mar 16 '23 00:03

aciurea