Reputation: 305
This may be really simple, but I've beat my head against the wall trying to figure it out.
I need to grab a value from a JSON response, but the key returned in the response is random, so I can't directly reference it to drill into it.
Here's the response I'm getting back:
var c = {
"success": {
"7d40ab5352b0471cae5bdefc2e032840": {
"__type__" : "user",
"__id__" : "7d40ab5352b0471cae5bdefc2e032840"
}
},
"errors": {}
}
What I need is the random string you see there - the ID. I've tried all kinds of things, and cannot for the life of me figure out how to get the ID back as a string. I've tried getting at it with array notation c.success[0][0]
to no avail. Obviously, I can't use dot notation, since I don't know what to put after .success.
Anyone know what to do in a situation where the keys of the array aren't known beforehand? I want to make sure that I do this in a way that's considered the best practice, not a hack.
Thanks...and if I've somehow missed an answer to this that's otherwise published, please send me that way. I've searched for days and can't find this answer.
Upvotes: 2
Views: 147
Reputation: 14345
for (var prop in c.success) {
alert(c.success[prop].__id__); // Replace the alert with whatever you want to do with the ID
// break; // Uncomment if there can be more than one ID returned and you only want one
}
and if the key is the same as the __id__
value, you can simply do:
for (var prop in c.success) {
alert(prop); // Replace the alert with whatever you want to do with the ID
// break; // Uncomment if there can be more than one ID returned and you only want one
}
Although Šime Vidas's use of Object.keys is more elegant, you will need the above code to work in older browsers unless you use what is called a him (i.e., you add some extra code which lets you use new standards today--i.e., an implementation of Object.keys which does the same thing as I did above, unless a built-in version already exists, in which case the shim will give preference to the built-in version).
Upvotes: 2
Reputation: 664548
You can use a simple loop:
for (var id in c.success) {
var obj = c.success[id];
// do something
}
If you want to ensure that only the first property in the object will be handled, you can add a break;
statement in the end.
Upvotes: 0
Reputation: 185923
This:
var obj = c.success[ Object.keys( c.success )[0] ];
obj.__type__ // "user"
obj.__id__ // "7d40ab5352b0471cae5bdefc2e032840"
Live demo: http://jsfiddle.net/AJaBS/
Upvotes: 2