suresh.maurya
01-17-2012, 04:04 AM
Hi,
I am a begginer in javascript, please help on below
I want to create an object with nested objects array like following:
var country{
var states=new array();
}
var state
{
city,pincode
}
this should be called like
var city= country[0].state[0].city;
any idea will be appreciated
Old Pedant
01-17-2012, 04:16 AM
How about something like this, instead of using numbers?
var countries = {
"USA" : {
"Alabama" : {
"Birmingham" : 371,
"Montgomery" : 8771 },
"Alaska" : {
"Anchorage" : 9918,
"Nome" : 8171 },
"Wyoming" : {
"Casper" : 718,
"Cody" : 888 }
},
"Canada" : [
"Alberta" : {
"Calgary" : "Z871" },
"British Columbia" {
"Vancouver" : "B88C",
"Victoria" : "C99A" },
...
};
var pin = countries["USA"]["Alaska"]["Nome"];
suresh.maurya
01-17-2012, 04:49 AM
Thanks Pedant for your reply,
this is exactly what i was trying to create, but i want to fill data in this countries object dynamically not hard coded.
which is my real problem.
Old Pedant
01-17-2012, 07:20 AM
No problem.
You could do it one step at a time, like this:
var countries = [ ];
countries["USA"] = [ ];
countries["USA"]["Alaska"] = [ ];
countries["USA"]["Alaska"]["Anchorage"] = 7183;
countries["USA"]["Alaska"]["Nome"] = 9378;
or in variations on that. Example:
var california = [ ];
california["Los Angeles"] = 91010;
california["San Francisco"] = 95004;
var texas = [ ];
texas["Dallas"] = 71822;
texas["San Antonio"] = 78811;
...
var usa = [ ];
usa["California"] = california;
usa["Texas"] = texas;
...
var countries = [ ];
countries["USA"] = usa;
...
Or variations in between.
suresh.maurya
01-17-2012, 10:46 AM
Thanks , this is really helpful to me.
devnull69
01-17-2012, 02:00 PM
You should use {} instead of [] when creating the object in the first place. This will create a JSON compatible object ... if you ever plan to convert it using JSON.stringify() etc
Example:
var countries = {};
countries["USA"] = {};
countries["USA"]["Alaska"] = {};
countries["USA"]["Alaska"]["Anchorage"] = 7183;
countries["USA"]["Alaska"]["Nome"] = 9378;
alert(JSON.stringify(countries)); // will give you a valid JSON string representation