0

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!

3
  • Please provide your code where you managed to assign objects. Just structure[obj] is not an assignment but an expression. Commented Oct 9, 2016 at 21:09
  • Here is the code: var structure = {} function addObject(object){ structure[object] = ""; } function ObjectToObject(object2,object) { structure[object][object2] = ""; } addObject("foo"); ObjectToObject("bar","foo"); Commented Oct 9, 2016 at 21:15
  • Best to edit your question (for readability of the code) Commented Oct 9, 2016 at 21:16

2 Answers 2

1

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

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

Comments

0

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

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.