Вопрос

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?

Это было полезно?

Решение 2

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 } };

Другие советы

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.

Use the following syntax:

C = {"A":"a","B":"b","C":"c"};
C.D = {"E":e};
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top