1

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
3
  • 1
    Your question is quite unclear. What are you trying to do, and how do you know that it's not working? Commented 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. Commented 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 working Commented Mar 13, 2017 at 4:29

5 Answers 5

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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);
answered Mar 13, 2017 at 4:28

1 Comment

i edited the question, i need to create the object not access it
0

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

Comments

0
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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.