Casey Crookston
Casey Crookston

Reputation: 13945

Add child object with value to existing javaScript object

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.

Upvotes: 4

Views: 7343

Answers (3)

HARMANPREET KAUR
HARMANPREET KAUR

Reputation: 11

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

Result:

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

Upvotes: 0

nanobar
nanobar

Reputation: 66345

myObject.myChildObject = 'foo'

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

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

Upvotes: 9

Mustafa Mamun
Mustafa Mamun

Reputation: 2661

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

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

Upvotes: 3

Related Questions