how to get the value of the only key-value pair in object [duplicate]

删除回忆录丶 提交于 2020-01-14 03:06:07

问题


I have a javascript object like below, a has only one key-value pair, how could I get the value of a1 without using iteration and also without knowing the key name(i.e a1) ?

a: {
            a1:"hello"
        }

回答1:


Since you said you know there's only one key–value pair in the object:

var a = { a1: 'hello' };
Object.keys(a)[0];
var key = Object.keys(a)[0];
a[key]; // yields "hello"



回答2:


You have to loop through i belive.

var t = { 
         a: {
              a1:"hello"
            }
        }

for (u in t) {
    console.log(u); //Outputs "a"
    for (v in t[u]) {
        console.log(v + " " +t[u][v]); //Ouputs "ai hello"
    } 
}


来源:https://stackoverflow.com/questions/24927783/how-to-get-the-value-of-the-only-key-value-pair-in-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!