[ACCEPTED]-Passing in dynamic key:value pairs to an object literal?-javascript
Accepted answer
EDIT: Use var obj = {}; obj[key] = chunks[i];
Because ECMAScript treats the 1 key
in this {key:1}
as literal.
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 }));
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
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.