[ACCEPTED]-Passing in dynamic key:value pairs to an object literal?-javascript

Accepted answer
Score: 31

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

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

Score: 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 1 brackets around the key)

Or better yet:

const Parameters = chunks.map((c, i) => ({ [`key_${i}`]: c }));
Score: 0

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

var obj = {
    test:1
}


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

Here 1 obj.key will not work

More Related questions