简体   繁体   English

如何添加将多个对象添加到同一索引

[英]How to add add multiple object into a same index

I wanted to create a multi dimensional object. 我想创建一个多维对象。 Below is my sample code. 以下是我的示例代码。 I'm not very familiar in JavaScript. 我对JavaScript不太熟悉。

Sample code 样例代码

var test = {};

test[0] = {1:{a:1,b:2,c:3}};

if(true)
{
  test[0] = {2: {c:1,b:2,a:3}};
}

console.log(test);

Expecting result 预期结果

{
  0: {
       1:{a:1,b:2,c:3},
       2:{c:1,b:2,a:3}  
     }
}

The second time you set test[0] , you're overwriting it completely. 第二次设置test[0] ,您将完全覆盖它。 To do exactly what you're looking for, you'd use: 要完全按照您的要求进行操作,可以使用:

test[0][2] = {c:1,b:2,a:3};

Depending on what you're doing though, you might consider an array [] or Set instead. 根据您的操作,可以考虑使用数组[]或Set。

You can Try this : 您可以尝试:

var obj = { 
  0: { 
    1:{a:1,b:2,c:3},
    2:{c:1,b:2,a:3} 
  }
} ;
// to access :
alert(obj[0][1].b);
// Or
alert(obj[0][1]["b"]);

Run and test it in here . 这里运行并进行测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM