Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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)
}
like image 507
cube Avatar asked Nov 07 '10 19:11

cube


People also ask

How do you add a key-value pair in an object dynamically?

To add dynamic key-value pairs to a JavaScript array or hash table, we can use computed key names. const obj = {}; obj[name] = val; to add a property with the value of name string as the property name. We assign val to as the property's value.


1 Answers

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 }));
like image 144
Paul Tyng Avatar answered Oct 24 '22 05:10

Paul Tyng