本文介绍了访问对象上Symbol(id)属性的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从第三方API获取的对象,如下所示:

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

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

仅通过 object.name 即可访问"Luke Skywalker",如何访问该对象的Symbol(id)属性的值?

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?

推荐答案

该对象初始化程序无效,因此很难回答.

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.

如果不是,则只能通过getOwnPropertySymbols发现符号.如果这是唯一的一个,那就太好了,您的身体状况良好:

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

假设只有一个以符号命名的属性,我们可能不应该这样做.取而代之的是让我们查找具有描述性字符串"Symbol(id)"的Symbol:

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

但是,如果它是全局注册的,并且您知道它在什么字符串下注册,则可以使用Symbol.for来获取它:

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

这篇关于访问对象上Symbol(id)属性的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 05:07