I need to create a nested object that looks like this
var a = "example"
{Chatting : {a :{ 'id' :a}}}
I can't really find anything online, I tried the code below and its not working
myobj['Chatting'][a] = {
'id': a
}
asked Mar 13, 2017 at 4:22
slimboy
1,6532 gold badges26 silver badges47 bronze badges
-
1Your question is quite unclear. What are you trying to do, and how do you know that it's not working?hughes– hughes2017年03月13日 04:24:57 +00:00Commented Mar 13, 2017 at 4:24
-
Describe what 'not working' is and what you are actually trying to accomplish. In the example you've listed, it's probably down to your indices not being literals.pvg– pvg2017年03月13日 04:27:56 +00:00Commented Mar 13, 2017 at 4:27
-
Im sorry i have a variable a, and I need to create a nested object using the variable but its just not workingslimboy– slimboy2017年03月13日 04:29:05 +00:00Commented Mar 13, 2017 at 4:29
5 Answers 5
To access the id property of the nested myObj you can try this:
var myObj={Chatting : {a :{ 'id' : 'a'}}};
alert(myObj.Chatting.a.id)
TO create a nested Object:
var Obj = { };
Obj["nestedObj"] = {};
Obj["nestedObj"]["nestedObj1"] = "value";
console.log(Obj);
answered Mar 13, 2017 at 4:27
Anonymous
1,9882 gold badges19 silver badges28 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
At once:
var a = "example"
var obj = {Chatting : {a :{ 'id' :a}}};
console.log(obj);
Step by step:
var a = "example"
var obj = {}; // create the object obj
obj.Chatting = {}; // create the sub-object Chatting of obj
obj.Chatting.a = {}; // create the sub-object a of Chatting
obj.Chatting.a.id = a; // set it's id to a
console.log(obj);
answered Mar 13, 2017 at 4:36
ibrahim mahrir
31.8k5 gold badges50 silver badges78 bronze badges
Comments
Your question is quite unclear. But i guess, you want get element a, right?
let a = {Chatting : {a :{ 'id' : 'a'}}};
console.log(a.Chatting.a);
1 Comment
slimboy
i edited the question, i need to create the object not access it
attribute names cannot be objects. (string variables are fine)
var a = "example";
var myObj = {
Chatting: {
a: { // here it is assumes to be "a"
"id": a // here exapmle is being stored in to "id"
}
}
}
console.log(myObj["Chatting"]["a"])// will let you access it
answered Mar 13, 2017 at 4:37
user1496463
4103 silver badges14 bronze badges
Comments
var a = "example";
var obj = {Chatting : {a :{ 'id' :'a'}}};
Please note that in an object {key:value} key is a string not variable. I am defining here id:'a', which will output
console.log(obj['Chatting']['a']['id']); // 'a'
and adding variable to the object
obj['Chatting']['a'] = {'id':a};
which will output
console.log(obj['Chatting']['a']['id']); // 'example'
answered Mar 13, 2017 at 4:40
lkdhruw
5821 gold badge7 silver badges23 bronze badges
Comments
lang-js