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:
const 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 description "id"
:
const data = {
name: "Luke Skywalker",
__typename: "People",
[Symbol("id")]: "ROOT_QUERY.people.",
};
const sym = Object.getOwnPropertySymbols(data).find(
(s) => s.description === "id"
);
console.log(sym ? data[sym] : "Symbol(id) not found");
I should note that it's perfectly valid for more than one Symbol to have the same description, so the above again is using the first one it finds, but while it would be odd, there could be more than one:
const data = {
name: "Luke Skywalker",
__typename: "People",
[Symbol("id")]: "Value for the first Symbol(id)",
[Symbol("id")]: "Value for the second Symbol(id)",
};
const idSymbolKeys = Object.getOwnPropertySymbols(data).filter(
(s) => s.description === "id"
);
console.log("'id' symbols found:", idSymbolKeys.length);
console.log(data[idSymbolKeys[0]]);
console.log(data[idSymbolKeys[1]]);
But if it's globally-registered and you know what string it's registered under, you can use Symbol.for
to get it:
const data = {
name: "Luke Skywalker",
__typename: "People",
[Symbol.for("id")]: "ROOT_QUERY.people.",
};
console.log(data[Symbol.for("id")]);