I have a problem. I need access to the object within the array on jQuery.
My json:
{"employ": [
{
"id": 46846,
"name": "some name",
"schedule": "main",
"hours": {
"11.09.2012": 5,
"12.09.2012": 8
}
}
,
{
"id": 3543,
"name": "another name",
"schedule": "main",
"hours": {
"11.09.2012": 9,
"12.09.2012": 7
}
}
]}
And my jquery:
$(document).ready(function(){
$("#click").click(function(){
$.getJSON('employ.json', {}, function(json){
$("#userid").append(json.employ[0].hours.????);
});
})
});
What code I need in the place with “????” to access element with name “11.09.2012” ?
Just use
["key"]to “index” it, like:JavaScript objects allow for two ways to access its items; either use dot notation (
.name) or bracket notation (["name"]). Obviously,["name"]is used in several occasions, such as yours (where the item contains an invalid identifier). Either way is allowed and just depends on preference and the situation.When not directly working with JSON, JavaScript objects don’t require each item to be declared as a string, so you could have:
And it’s perfectly valid. But in this type of declaration, you can only use valid characters that are used for naming normal variables (as a valid identifier). So for this case, you should always be able to use dot notation.
When working with actual JSON communication, all keys (items) are stored as strings, so “invalid” characters are allowed. But if the key contains an invalid character, you must use bracket notation (
[]).[]is the safest way to get and set items, especially dynamically. And by dynamic, I mean doing something like:In the above, you can’t do something like:
and have it do what you want.