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!
2 Answers
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);
structure[obj]is not an assignment but an expression.