Search code examples
javascriptsymbols

JS Symbol as object key


I'm running a node software where in a certain context of the software there is an object which one of it's keys is a Symbol, and it's value is an object. For example:

object = {Symbol(symbol_name): another_object}

I'm trying to get to the 'another_object' keys and values and can't find the way to do so. Suggestions anyone?


Solution

  • The best approach would be to save the Symbol in a variable first, then just use bracket notation to look it up:

    const sym = Symbol('symbol_name');
    const object = {[sym]: { foo: 'bar' }}
    
    console.log(object[sym]);

    If you don't have a reference to the symbol, and the object contains only one symbol, you can get it with getOwnPropertySymbols:

    const object = {
      [Symbol('symbol_name')]: {
        foo: 'bar'
      }
    };
    
    const sym = Object.getOwnPropertySymbols(object)[0];
    console.log(object[sym]);