If you know that always the name of the key you want is "key1" as shown in the example, you can use the following function:
var obj = {
"id1": {
"key1": "valueX",
"key2": "dont care"
},
"id2": {
"key1": "valueY",
"key2": "dont care"
},
"id3": {
"key1": "valueZ",
"key2": "dont care"
}
};
var getFirstChild = function(obj, key) {
return obj[key].key1;
}
alert(getFirstChild(obj, 'id2'));
First you get the object that has the specified key, and then you search for the pair with the key1 key.
If you want to get the first key of the object, regardless of the name you can use the following:
var obj = {
"id1": {
"key1": "valueX",
"key2": "dont care"
},
"id2": {
"key1": "valueY",
"key2": "dont care"
},
"id3": {
"key1": "valueZ",
"key2": "dont care"
}
};
var getFirstChild = function(obj, key) {
return obj[key].key1;
}
alert(getFirstChild(obj, 'id2'));
This will again search for the key you specify, get all the values, and return the first. Note that properties are ordered inside object depending on javascript implementation. Meaning that the first property you specify in your code, might not be the first property in the object after all.