cube cube - 4 years ago 141
Javascript Question

Passing in dynamic key:value pairs to an object literal?

I am using this slice of code (shown below) in an attempt to populate the object literal named

inside the for loop. I need the
pair to be assigned in conjunction with the loops iterating
variable, as such:
. However, my code isn't working. The
is not being reflected in the literal.

There's something I am missing here, obviously. Can someone tell me what it is?...Thanks.

var Parameters=[];
var len = chunks.length;
for (var i = 0; i < len; i++) {
var key='key_'+i
obj= { key : chunks[i]};

Answer Source

EDIT: Use var obj = {}; obj[key] = chunks[i];

Because ECMAScript treats the key in this {key:1} as literal.

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