46

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!

1
  • 10
    Apropos best practices, {} instead of new Object(). Oct 30, 2011 at 0:12

4 Answers 4

90

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.

8
  • 2
    i suppose defaultsettings["ajaxsettings"]["somekey"] is equivalent to defaultsettings.ajaxsettings.somekey ?
    – Johan
    Oct 29, 2011 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, 2011 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 Nov 26, 2015 at 16:52
  • 1
    Please note that in ES6 you now can declare keys from variables using the object literal notation like so { [myVariable]: "myValue"}. Feb 8, 2017 at 17:14
  • 1
    @sigmapi13 - keyname is a variable, it's not supposed to have quotes around it.
    – nnnnnn
    Feb 24, 2017 at 12:04
13
var defaultsettings = {
    ajaxsettings: {
        ...
    },
    uisettings: {
        ...
    }
};
3
  • 1
    Do i need to declare ajaxsettings as a new object outside defaultsettings?
    – Johan
    Oct 29, 2011 at 23:45
  • No, just build exactly like that. Oct 29, 2011 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, 2011 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.

3
  • regarding JSON.stringify(), i suppose thats not included in jquery?
    – Johan
    Oct 29, 2011 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, 2011 at 0: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, 2011 at 15:51
0

It's been a pain to get JS Objects working as array.push

I have therefore developed a small code that may give you a desired nested outcome:

var obj = {};

var obj2 = {name:'John',age:55};

var fin = function (obj01,obj02){
   return obj01['obj02'] = {};

};

var nestObj = fin(obj,obj2);

var fin2 = function(nestObj2){
nestObj2.name = obj2.name;
nestObj2.age = obj2.age;
}

fin2(nestObj);
console.log(obj);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.