I need your help with the json structure !! (I know it’s easy but I cann’t figure what the error is).
in this code I’m having a json file that contains a list of items (say restaurants) along with some details for each branch, like the address. In my js file I’m trying to print all the addresses that match specific item id.
I will post a sample of the json file and the js code to access it.
here is the json file:
{
"items" :
[
{
"item_id" :"204","details" :[{"country":"usa","city":"NY", "address":"bla bla bla"},{"country":"usa","city":"NY", "address":"another bla bla bla for the same id"}]
},
{
"item_id" :"234","details" :[{"country":"usa","city":"NY", "address":"another bla bla bla"}]
}
]
}
and here is the js code to access that file:
.....
success:function(data){
$.each(data.items, function(i,item){
if (item.item_id == 204 ) {
$("#results").append("<hr/>");
$("#results").append("<span class='result' >" + item.details.address + "</span><br/>");
}
});
}, ....
but it doesn’t print any thing.
What do you think?
You don’t actually need to use $.each in this case, because you have an array of objects i.e.
[{}, {}, {}]is an array of objects, even though you actually have an object of arrays of objects :p. Each object has a specified index i.e. “item” whereas each array of objects has a default index of 0,1,2 etc.Also yeah, because you have an array of address object details, you need to access them via
details[0]ordetails[1]Check this example out on jsFiddle