Reputation: 13955
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.
Upvotes: 0
Views: 1331
Reputation: 86
No idea what your question means but myObject["foobar"] might be what you are looking for
Upvotes: 0
Reputation: 2304
I'd say
for(var key in myChildObject) {
myObject[key] = myChildObject[key]
}
Upvotes: 0
Reputation: 2661
var myObject = {};
var myChildObject = this.name.split('.')[1];
myObject[myChildObject] ={
"thing1":25,
"thing2":6
};
Upvotes: 1
Reputation: 317
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
Upvotes: 1
Reputation: 216
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.
Upvotes: 2