11

I am using this slice of code (shown below) in an attempt to populate the object literal named Parameters inside the for loop. I need the key:value pair to be assigned in conjunction with the loops iterating i variable, as such: {key_1:chunks[1],key_2:chunks[2]}. However, my code isn't working. The 'key_'+i 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]};
   Parameters.push(obj)
}
cube
  • 1,774
  • 4
  • 23
  • 33
  • 1
    Similar question that may be helpful to you: http://stackoverflow.com/questions/1998735/dynamic-object-literal-in-javascript – DaiYoukai Nov 07 '10 at 19:52

3 Answers3

31

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

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

meder omuraliev
  • 183,342
  • 71
  • 393
  • 434
  • Yes made a typo in the question only. Should have been `var Parameters=[];`. The question/problem still stands though. – cube Nov 07 '10 at 19:45
5

ES2015 (via Babel) Supports dynamic keys:

const Parameters=[];
const len = chunks.length;
for (let i = 0; i < len; i++) {
    const key = `key_${i}`;
    obj = { [key] : chunks[i]};
    Parameters.push(obj);
}

(note the brackets around the key)

Or better yet:

const Parameters = chunks.map((c, i) => ({ [`key_${i}`]: c }));
Paul Tyng
  • 7,924
  • 1
  • 33
  • 57
0

same can be used for lookup: obj[key] . Do remmeber obj.key will look for key in object

var obj = {
    test:1
}


var key = 'test'
obj.test = obj[key] = 1

Here obj.key will not work

Soman Dubey
  • 3,798
  • 4
  • 22
  • 32