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

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

    That object initializer is invalid, so it's hard to answer.

    If that really is a Symbol-named property, the answer depends on whether the Symbol is globally-registered.

    If it isn't, you can only discover the symbol via getOwnPropertySymbols. If it's the only one, great, you're in good shape:

    var data = {
        name:"Luke Skywalker",
        __typename:"People",
        [Symbol("id")]:"ROOT_QUERY.people."
    };
    console.log(data[Object.getOwnPropertySymbols(data)[0]]);

    That assumes that there's only one Symbol-named property, which we probably shouldn't do. Instead, let's look for the Symbol with the descriptive string "Symbol(id)":

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


    But if it's globally-registered and you know what string it's registered under, you can use Symbol.for to get it:

    var data = {
        name:"Luke Skywalker",
        __typename:"People",
        [Symbol.for("id")]:"ROOT_QUERY.people."
    };
    console.log(data[Symbol.for("id")]);

提交回复
热议问题