Javascript获取对象属性名称 [英] Javascript get Object property Name

查看:84
本文介绍了Javascript获取对象属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我传递了以下对象:

var myVar = { typeA: { option1: "one", option2: "two" } }

我希望能够提取密钥 typeA 来自上述结构。

I want to be able to pull out the key typeA from the above structure.

此值每次都可以更改,以便下次可以 typeB

This value can change each time so next time it could be typeB.

所以我想知道是否有办法让我做类似下面的伪代码:

So I would like to know if there is a way for me to do something like the following pseudo code:

var theTypeIs = myVar.key();

这样当我可以传递这个对象并且我可以拉出对象的第一个值时,这种情况是 typeA 然后根据我可以用 option1 做不同的事情option2

This way when I can pass this object and I can pull out the first value of the object, in this case it is typeA and then based on that I can do different things with option1 and option2.

推荐答案

如果你确定在那里肯定只有一把钥匙对象,然后你可以使用 Object.keys

If you know for sure that there's always going to be exactly one key in the object, then you can use Object.keys:

theTypeIs = Object.keys(myVar)[0];

这篇关于Javascript获取对象属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆