Access the value of Symbol(id) property on an object

前端 未结 4 607
太阳男子
太阳男子 2021-02-02 16:22

I have an object fetched from 3rd party API as shown below:

{
    name:\"Luke Skywalker\",
    __typename:\"People\",
    Symbol(id):\"ROOT_QUERY.people.\"
}
         


        
4条回答
  •  难免孤独
    2021-02-02 16:50

    You can use Object.getOwnPropertySymbols() to retrieve it, but this would retrieve all symbols tied to an object. If you want to get that particular symbol on the object directly, you need to store that Symbol object else to be re-used.

    const sym = Symbol(id);
    const example = {
      name:"Luke Skywalker",
      __typename:"People",
      [sym]:"ROOT_QUERY.people."
    }
    
    console.log(example[sym]) //Equals "ROOT_QUERY.people."
    

提交回复
热议问题