在嵌套对象中添加变量

时间:2017-03-13 04:22:04

标签: javascript node.js

我需要创建一个看起来像这样的嵌套对象

var a = "example"
{Chatting : {a :{ 'id' :a}}}

我无法在网上找到任何内容,我尝试了下面的代码并且无法正常工作

myobj['Chatting'][a] = {
'id': a
 }

5 个答案:

答案 0 :(得分:1)

立刻:

var a = "example"
var obj = {Chatting : {a :{ 'id' :a}}};

console.log(obj);

一步一步:

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

答案 1 :(得分:0)

要访问嵌套myObj的id属性,您可以尝试:

var Obj = { };
Obj["nestedObj"] = {};
Obj["nestedObj"]["nestedObj1"] = "value";
console.log(Obj);

创建嵌套对象:

counter <- 0
g <- function(){
f <- function(){
  counter <- counter + 1
  print(counter)
}
f()
f()
f()
}
g()
g()
g()

答案 2 :(得分:0)

你的问题很不清楚。 但我想,你想得到元素a,对吗?

let a = {Chatting : {a :{ 'id' : 'a'}}};
console.log(a.Chatting.a);

答案 3 :(得分:0)

属性名称不能是对象。 (字符串变量很好)

override

答案 4 :(得分:0)

Consider using abstract classes if any of these statements apply to your situation:
    You want to share code among several closely related classes.
    You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
    You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.
Consider using interfaces if any of these statements apply to your situation:
    You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
    You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
    You want to take advantage of multiple inheritance of type.

请注意,在对象{key:value}中,键是一个不可变的字符串。我在这里定义id:'a',它将输出

var a = "example";
var obj = {Chatting : {a :{ 'id' :'a'}}};

并向对象添加变量

console.log(obj['Chatting']['a']['id']); // 'a'

将输出

obj['Chatting']['a'] = {'id':a};