Reputation: 20438
Soccer
Australia
Melbourne
Sydney
New Zealand
Christchurch
Tennis
United Kingdom
Kensington
London
Manchester
I have tried multidimensional arrays however it becomes awkward because of the different lengths. I have also experimented with key/value pairs however again I encountered difficulty because in a way there are only values and no keys. I have tried to represent the hierarchy visually. To clarify Sydney is a child of Australia. Australia is a child of Soccer. Soccer is a sibling of Tennis and so on.
Edit: I'm looking for a solution that does not require any knowledge of the actual data. In other words I could swap out "Soccer" with "Baseball" and a simple algorithm which just prints out the data structure should not break.
Upvotes: 0
Views: 207
Reputation: 23250
In JSON:
{
"Soccer": {
"Australia": [
"Melbourne",
"Sydney"
],
"NewZealand": [
"Christchurch"
]
},
"Tennis": {
"UnitedKingdom": [
"Kensington",
"London",
"Manchester"
]
}
}
Here's a loop through the data:
for ( sport in data ) {
// print sport here
countries = data[sport];
for ( country in countries ) {
// print country here
cities = countries[country];
for (var i = 0; i < cities.length; i++) {
// print city here
};
};
};
Can be seen on jsFiddle here: http://jsfiddle.net/2p6g3/18/
Upvotes: 4
Reputation: 444
{
"sport": [
{
"name": "Soccer",
"place": [
{
"country": "Australia",
"city": [
{
"name": "Melbourne"
},
{
"nam": "Sdney"
}
]
},
{
"country": "NewZealand",
"city": [
{
"name": "Christchurch"
}
]
}
]
},
{
"name": "Tennis",
"place": [
{
"country": "UnitedKingdom",
"city": [
{
"name": "Manchester"
}
]
}
]
}
]
}
loop through the array of object to get required fields:
sport[].name // name of the sports
sport[].place[].country // country name
sport[].place[].city[].name // city name
Upvotes: 0