0

Let's say I have a blank JavaScript object:

myObject {}

And I also have a variable:

var myChildObject = this.name.split('.')[1];

For the sake of an example, let's say that myChildObject equals "FooBar". Now, I want to add a child object to myObject with the name of "FooBar", only we can't hard code "FooBar". We have to use the variable name myChildObject.

I tried this:

myObject.appendChild(myChildObject);

That doesn't work.

The goal is this:

{  
   "myObject":{  
      "FooBar":{  
         "thing1":25,
         "thing2":6
      },
      .....
}

But I need to build the entire thing dynamically, without the names (other than the root) being known ahead of time.

Casey Crookston
  • 13,016
  • 24
  • 107
  • 193

5 Answers5

2

An object is a "key value" type of thing, a little bit like a Map in Java. have you tried something like this:

let myObject = {};
let myChildObject = "fooBar";
myObject[myChildObject] = {};

This way you have a "fooBar" key for your Object... now you have to decide what you want the value to be for that key.

ChaudPain
  • 216
  • 1
  • 11
1
var myObject = {};
var myChildObject = this.name.split('.')[1];
myObject[myChildObject] ={  
     "thing1":25,
     "thing2":6
  };
Mustafa Mamun
  • 2,591
  • 2
  • 14
  • 17
1

Objects can only have key value pair. You cannot use one without other. If you don't want to assign a value then simply give undefined. If you don't know the name of the property then you can simply use the array type notation for an object "[]". Refer to code below

var myObject = {};
var myChildObject = this.name.split('.')[1];

myObject[myChildObject] = undefined;

console.log(myObject.hasOwnProperty(myChildObject)); // true
Sam
  • 317
  • 3
  • 12
0

I'd say

for(var key in myChildObject) {
  myObject[key] = myChildObject[key]
}
ValLeNain
  • 2,232
  • 1
  • 18
  • 37
0

No idea what your question means but myObject["foobar"] might be what you are looking for