1

Assuming I have an object literal that looks like this:

C = {"A":"a","B":"b","C":"c"};

and I want to add another object like this..

"D" : {"E":e}

where e is a variable. and e = "ValueOfE" So that C will have this kind of value..

C = {"A":"a","B":"b","C":"c", "D" : { "E" : "ValueOfE"}};

How will I do that?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
srh snl
  • 797
  • 1
  • 19
  • 42

3 Answers3

2

Let's say you have your C object literal like:

C = {"A":"a","B":"b","C":"c"};

you can add any other objects to it like:

var D = { "E" : e};
C["D"] = D;

or simply:

C["D"] = { "E" : e};

and if your key("D") is a valid identifier, which in this case is, you can also do it like:

C.D = { "E" : e};

Other than that in some older browsers you couldn't use unquoted reserved words. For instance ES3 didn't allow the use of unquoted reserved words as property names such as : default, delete, do, double, else, enum ,... which are not the case here.

You could also create your object using literal and pass the D object:

C = {"A":"a","B":"b","C":"c", "D":D };

and also:

C = {"A":"a","B":"b","C":"c", "D": { "E" : e } };

The point is JavaScript objects are kind of HashMaps with keys and values, and using literal syntax you can create it with all the other objects and values in it. and also you can add new key value pairs after the object gets created.

Mehran Hatami
  • 12,723
  • 6
  • 28
  • 35
  • *"and if your key("D") is not a reserved keyword..."* The property name just have to be a valid identifier name. So e.g. `C.if = 'foo';` is perfectly valid, but it could lead to problems in older browsers. So, technically you can use dot notation also if the property name is a reserved keyword, but it's better if you don't. – Felix Kling Mar 10 '14 at 05:36
1

The values in object literals can be arbitrary expressions, which means that they can contain other object literals, make use of existing variables, and so on; so if you're asking what I think you are, then you can write:

C = { "A": "a", "B": "b", "C": "c", "D": { "E": e } };
ruakh
  • 175,680
  • 26
  • 273
  • 307
1

Use the following syntax:

C = {"A":"a","B":"b","C":"c"};
C.D = {"E":e};
Minko Gechev
  • 25,304
  • 9
  • 61
  • 68