4

I have an empty root object created in JavsScript:

var myObject = {};

Now, I want to add a child object with a value:

{  
   "myObject ":{  
      "myChildObject":"FooBar"
   }
}

Seems simple enough, but I'm having a hard time finding an answer. Most of the examples I find are related to DOM objects (div's) and don't really translate well. I've been looking at W3Schools on their .appendChild() page, but the examples there don't set a value.

1
  • myObject.myObject.myChildObject = 'FooBar'; Commented Jan 23, 2017 at 18:25

3 Answers 3

9

myObject.myChildObject = 'foo'

or, if your key has spaces in it you can use square bracket notation:

myObject['my Child Object'] = 'foo'

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

Comments

3

If You want to add a child to myObject then just do it

var myObject = {};
myObject.myChildObject = "Foo Bar"

Comments

0
var myObject = {};
myObject.myObject = Object.assign({myChildObject:"red"});
console.log(myObject);

Result:

{  
   "myObject ":{  
      "myChildObject":"FooBar"
   }
}

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.