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(). Commented Oct 30, 2011 at 0:12

4 Answers 4

91

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.

Sign up to request clarification or add additional context in comments.

8 Comments

i suppose defaultsettings["ajaxsettings"]["somekey"] is equivalent to defaultsettings.ajaxsettings.somekey ?
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.)
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
Please note that in ES6 you now can declare keys from variables using the object literal notation like so { [myVariable]: "myValue"}.
@sigmapi13 - keyname is a variable, it's not supposed to have quotes around it.
|
13
var defaultsettings = {
    ajaxsettings: {
        ...
    },
    uisettings: {
        ...
    }
};

3 Comments

Do i need to declare ajaxsettings as a new object outside defaultsettings?
No, just build exactly like that.
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.
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 Comments

regarding JSON.stringify(), i suppose thats not included in jquery?
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.)
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?
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);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.