Arkoudinos
Arkoudinos

Reputation: 1128

How to create dynamic array element names in JavaScript, inside a for loop?

I have a for loop in a JS snippet and I want to dynamically generate the array members' names, based on a string and the current iteration number. Basically I have written something like this:

product_data[i] = {
  "ch-" + i: '1',
  'product' + i: jsondata[products][i].product_description,
  'quantity' + i: jsondata[products][i].quantity,
  'price' + i: jsondata[products][i].unit_price,
  'rem' + i: '',
  'fpa' + i: jsondata[products][i].vat
};

however, it's not working at all. I've used eval() without any luck too. Any ideas?

Upvotes: 2

Views: 1924

Answers (3)

canon
canon

Reputation: 41675

If supported in your environment, you can use the new ECMAScript notation for computed property names in object initializers:

var product_data = new Array(2);

for (var i = 0; i < 2; i++) {
  product_data[i] = {
    ["ch-" + i]: i,
  };
}

console.log(product_data);

Otherwise, you can use good ol' bracket notation, like so:

var product_data = new Array(2);

for (var i = 0; i < 2; i++) {
  product_data[i] = {};
  product_data[i]["ch-" + i] = i;
}

console.log(product_data);

Upvotes: 1

sergio0983
sergio0983

Reputation: 1278

You can do it like this

product_data[i] = {};
product_data[i]["ch-"+i] = '1';
product_data[i]["product"+i] = jsondata[products][i].product_description;
...

And so on...

Upvotes: -1

iuliu.net
iuliu.net

Reputation: 7145

This features exists since ES6. You can use it like so:

var obj = {
  [myKey]: value,
}

So your example becomes:

product_data[i] = {
               ["ch-" + i]: '1',
               ['product' + i]: jsondata[products][i].product_description,
               ['quantity' + i]: jsondata[products][i].quantity,
               ['price' + i]: jsondata[products][i].unit_price,
               ['rem' + i]: '',
               ['fpa' + i]: jsondata[products][i].vat
               };

If you want to don't want to use EcmaScript 6, you'll have to initialize your object as an empty one and then add the properties to it:

product_data[i] = {};
product_data[i]["ch-" + i] = '1'
...

Upvotes: 1

Related Questions