简体   繁体   中英

How to dynamically add objects to objects inside of an object

So I have an object: structure = {} and I can dynamically add an object to it with structure[obj] , but I need to be able to add yet another object inside of that. I tried doing structure[obj][obj2] but that doesn't work. What is the proper way to do this? Thanks!

If you have assigned an

structure["foo"] = {bar: 1}

You can then assign a further element like this

structure["foo"]["harry"] = 99;

But you can't do it without the first step, because structure["foo"] won't exist yet

With this statement:

structure[object] = "";

You are not adding an object to structure , but an empty string, which is a primitive value, not an object. Also the name object is misleading in your code, as apparently you have a string value for it ( 'foo' ). But even if it were a true object, by using it in the above statement, JavaScript will take the string value of it (which would be 'Object object' for plain objects) and use it as a key (property) in structure .

Look at the whole piece of code:

var structure = {} 
function addObject(object){ 
    structure[object] = ""; 
} 
function ObjectToObject(object2, object) { 
    structure[object][object2] = ""; 
} 
addObject("foo"); 
ObjectToObject("bar","foo");

... the statement structure[object][object2] = ""; will be without effect. It comes down to this:

structure.foo.bar = "";

As structure.foo is a string value, JavaScript will coerce it to a String object because otherwise it cannot apply .bar . So really this is what is executed:

new String(structure.foo).bar = "";

The assignment of '' is really made, but then that temporary object is disposed again, so that you never see that bar again.

How you should do it:

Don't asssign a string in the first function, but an empty object. Also use better names for your variables:

 var structure = {} function addObject(key){ structure[key] = {}; } function ObjectToObject(key2, key) { structure[key][key2] = {}; } addObject("foo"); ObjectToObject("bar","foo"); console.log(structure); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM