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
 }
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);

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);

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);

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

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'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.