问题
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