43

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!

Kobi
  • 135,331
  • 41
  • 252
  • 292
Johan
  • 35,120
  • 54
  • 178
  • 293

3 Answers3

88

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.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • 2
    i suppose `defaultsettings["ajaxsettings"]["somekey"]` is equivalent to `defaultsettings.ajaxsettings.somekey` ? – Johan Oct 29 '11 at 23:51
  • 2
    Yes it is. You can use dot notation as long as the key name follows the rules for valid JS identifier names, i.e., not starting with a number, not a JS reserved word, no spaces, etc. (All of those things are allowed if you use the square bracket syntax, indeed purely by accident my final example above did have a space in a key name.) – nnnnnn Oct 29 '11 at 23:56
  • is there any way to make my code like var obj = {}; //afer pushing the object should look like obj { 'a' : {'key':'value'}, 'b' : {'key':'value'} } //my code is var client = {}; client.push(socket.id:{[socket.id]:val}); //getting error missing ( argument – ujwal dhakal Nov 26 '15 at 16:52
  • @ujwaldhakal - `.push()` is an array method, you can't use it on a plain object. But the code shown in my answer shows how to get something like `{ 'a' : {'key':'value'}, 'b' : {'key':'value'} }` by adding objects and then adding properties to them. – nnnnnn Nov 28 '15 at 02:45
  • 1
    Please note that in ES6 you now can declare keys from variables using the object literal notation like so `{ [myVariable]: "myValue"}`. – Daniel Zendejas Feb 08 '17 at 17:14
  • 1
    @sigmapi13 - `keyname` is a variable, it's not supposed to have quotes around it. – nnnnnn Feb 24 '17 at 12:04
  • can I create nested object with no key { {}, {} ) ? – user269867 Nov 14 '17 at 00:19
  • @user269867 - The nested object can be empty, but it must be the value associated with a key of the containing object, so: `{ x: {}, y: {} }`. – nnnnnn Nov 14 '17 at 01:59
12
var defaultsettings = {
    ajaxsettings: {
        ...
    },
    uisettings: {
        ...
    }
};
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • 1
    Do i need to declare ajaxsettings as a new object outside defaultsettings? – Johan Oct 29 '11 at 23:45
  • No, just build exactly like that. – Niet the Dark Absol Oct 29 '11 at 23:46
  • No, it can all be declared like this. If you have another object that you want to set as your ajaxsettings, just list it on the other side of the : instead of the {}. Remember, to have the comma after all properties unless it is the last property in the list. – Brian Oct 29 '11 at 23:46
4
var defaultSettings = {
    ajaxsettings: {},
    uisettings: {}
};

Take a look at this site: http://www.json.org/

Also, you can try calling JSON.stringify() on one of your objects from the browser to see the json format. You'd have to do this in the console or a test page.

Brian
  • 3,571
  • 7
  • 44
  • 70
  • regarding JSON.stringify(), i suppose thats not included in jquery? – Johan Oct 29 '11 at 23:48
  • It's a pity somebody downvoted without explaining why (it wasn't me), but note that JS object literals and JSON are two different things. (And, ironically, the example code in your answer is not valid JSON.) – nnnnnn Oct 30 '11 at 00:01
  • I guess I incorrectly use the two as the same but I believe JSON is valid representation of a Javascript object except that it is a in a string. Understanding proper JSON notation would allow the OP to write proper object literals. I understand that what I wrote was not JSON, but as far as an object literal, it correct isn't it? – Brian Oct 30 '11 at 15:51