Monday, November 11, 2024

JavaScript How is property accessed when property of object is Symbol

When an object's property is a Symbol, you access it similarly to how you would access a property with a string key, but you must use the Symbol reference itself. Here are the ways to access a Symbol property:

1. Accessing Using Bracket Notation

Since the Symbol is a unique value, it needs to be referenced explicitly with bracket notation.
const mySymbol = Symbol('mySymbol');
const obj = {
  [mySymbol]: 'value'
};

// Access the property using bracket notation
console.log(obj[mySymbol]); // Output: 'value'

2. Using Object.getOwnPropertySymbols

If you don’t have direct access to the Symbol reference, you can retrieve all Symbol properties of an object using Object.getOwnPropertySymbols, which returns an array of Symbol keys.
const symbol1 = Symbol('symbol1');
const symbol2 = Symbol('symbol2');
const obj = {
  [symbol1]: 'value1',
  [symbol2]: 'value2'
};

const symbols = Object.getOwnPropertySymbols(obj);

// Access each symbol property
console.log(obj[symbols[0]]); // Output: 'value1'
console.log(obj[symbols[1]]); // Output: 'value2'

3. Using Reflect.ownKeys

The Reflect.ownKeys method returns all keys of an object, including both string and Symbol keys. This is useful if you want to retrieve all properties, regardless of type.
const mySymbol = Symbol('mySymbol');
const obj = {
  [mySymbol]: 'value',
  normalKey: 'normalValue'
};

const keys = Reflect.ownKeys(obj);
console.log(keys); // Output: ['normalKey', Symbol(mySymbol)]

// Access the Symbol property
console.log(obj[keys[1]]); // Output: 'value'

4. Passing the Symbol Directly if Available

If you have direct access to the Symbol (for example, if it's defined in the same scope), you can simply use obj[symbol]:
const mySymbol = Symbol('mySymbol');
const obj = {
  [mySymbol]: 'value'
};

// Directly access if the symbol is in scope
console.log(obj[mySymbol]); // Output: 'value'

Summary

  1. Bracket notation: Use obj[symbol] if you have the symbol reference.
  2. Object.getOwnPropertySymbols(obj): Use this to get all Symbol properties if you don’t have direct access.
  3. Reflect.ownKeys(obj): Use this if you need both string and Symbol properties.

No comments:

Post a Comment

Hot Topics