1

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"
        }
Blake
  • 7,367
  • 19
  • 54
  • 80
  • in my case, it's bit special because the object has only 1 key-value pair, so I am asking how to get the value **without using iteration** – Blake Jul 24 '14 at 07:47
  • that is the same situation as in the duplicate question – Thilo Jul 24 '14 at 07:48

2 Answers2

4

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"
2540625
  • 11,022
  • 8
  • 52
  • 58
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"
    } 
}
DC-
  • 797
  • 9
  • 14