Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
145
rated 0 times [  148] [ 3]  / answers: 1 / hits: 147243  / 13 Years ago, sat, october 29, 2011, 12:00:00

I would like to know the correct way to create a nested object in javascript. I want a base object called defaultsettings. It should have 2 properties (object type): ajaxsettings and uisettings. I know that i can write something like



var defaultsettings = new Object();
var ajaxsettings = new Object();

defaultsettings.ajaxsettings = ajaxsettings.. etc.


But what i want to know is how to type it this way (that i suppose is a more correct way of doing it):



var defaultsettings = { 
var ajaxsettings = { ... }
};


I suppose you get the idea. Thanks!


More From » object

 Answers
15

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.


[#89374] Friday, October 28, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaredsages

Total Points: 273
Total Questions: 97
Total Answers: 105

Location: French Southern and Antarctic Lands
Member since Fri, Jan 6, 2023
1 Year ago
jaredsages questions
;