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

前端 未结 4 594
太阳男子
太阳男子 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:59

    Adding to @T.J. Crowder, Symbols can also be discovered through Reflect.ownKeys which will list all object own keys: property names & symbols.

    const data = {
        name:"Luke Skywalker",
        __typename:"People",
        [Symbol("id")]:"ROOT_QUERY.people."
    };
    
    const sym = Reflect.ownKeys(data).find(s => {
      return String(s) === "Symbol(id)";
    });
    console.log(sym ? data[sym] : "Symbol(id) not found");

提交回复
热议问题