简体   繁体   中英

How to access values from this complex JavaScript Object?

I am working with AbsoluteOrientationSensor

I have an object that contains the values of the accelerometer of the phone.

The values that I need are nested inside an Symbol in the Object.

How do I access those values?

The Object Name is "message".

I have already tried this

console.log(message.__sensor__.quaternion);

But I am getting the result as "undefined".

I have never worked with the Symbol data type in JavaScript before.

The Values that I want to access are the quaternion values

This is the screenshot of the Object Structure -

我正在使用的对象

Thank you for your help.

From the documentation :

Properties

OrientationSensor.quaternion : Returns a four element Array whose elements contain the components of the unit quaternion representing the device's orientation.

So:

console.log(message.quaternion);

You can also see in the screenshot that the object itself has a getter quaternion .


I have never worked with the Symbol data type in JavaScript before.

Symbols are used for various reasons as property names, but if they are used, it almost always means that you, as a consumer of the API, are not supposed to access that value directly. Instead you should use the "public" API the object provides to access this data, such as in this case.

 function GetSymbol(object, name) { const string = `Symbol(${name})` return Object.getOwnPropertySymbols(object).find(symbol => symbol.toString() === string) } const __sensor__ = GetSymbol(message, "__sensor__") console.log(message[__sensor__]) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM