Monday, June 3, 2024
31
rated 0 times [  37] [ 6]  / answers: 1 / hits: 18059  / 7 Years ago, sat, june 24, 2017, 12:00:00

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



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


While Luke Skywalker can be accessed by simply object.name,
how can I get access to the value of Symbol(id) property of this object?


More From » ecmascript-6

 Answers
9

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)]);




[#57320] Thursday, June 22, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rohan

Total Points: 403
Total Questions: 93
Total Answers: 105

Location: Trinidad and Tobago
Member since Mon, Jul 13, 2020
4 Years ago
rohan questions
Tue, Sep 8, 20, 00:00, 4 Years ago
Fri, Aug 21, 20, 00:00, 4 Years ago
Mon, Aug 3, 20, 00:00, 4 Years ago
Thu, Jul 2, 20, 00:00, 4 Years ago
;