Nested objects in javascript, best practices
var defaultsettings = {
ajaxsettings: {
...
},
uisettings: {
...
}
};
If you know the settings in advance you can define it in a single statement:
var defaultsettings = {
ajaxsettings : { "ak1" : "v1", "ak2" : "v2", etc. },
uisettings : { "ui1" : "v1", "ui22" : "v2", etc }
};
If you don't know the values in advance you can just define the top level object and then add properties:
var defaultsettings = { };
defaultsettings["ajaxsettings"] = {};
defaultsettings["ajaxsettings"]["somekey"] = "some value";
Or half-way between the two, define the top level with nested empty objects as properties and then add properties to those nested objects:
var defaultsettings = {
ajaxsettings : { },
uisettings : { }
};
defaultsettings["ajaxsettings"]["somekey"] = "some value";
defaultsettings["uisettings"]["somekey"] = "some value";
You can nest as deep as you like using the above techniques, and anywhere that you have a string literal in the square brackets you can use a variable:
var keyname = "ajaxsettings";
var defaultsettings = {};
defaultsettings[keyname] = {};
defaultsettings[keyname]["some key"] = "some value";
Note that you can not use variables for key names in the { } literal syntax.