d3no d3no - 1 year ago 44
Javascript Question

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.

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

Answer Source

The second time you set test[0], you're overwriting it completely. 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download