John Doe John Doe - 9 months ago 47
Javascript Question

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?

Answer Source

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

var product_data = new Array(2);

for (var i = 0; i < 2; i++) {
  product_data[i] = {
    ["ch-" + i]: "1",
    ["product" + i]: "test",
    ["quantity" + i]: 2,
    ["price" + i]: 99.99,
    ["rem" + i]: "",
    ["fpa" + i]: "xxx"
  };
}

console.log(product_data);

Otherwise, you can use bracket notation for dynamic property names, like so:

var product_data = new Array(2);

for (var i = 0; i < 2; i++) {
  product_data[i] = {};
  product_data[i]["ch-" + i] = "1";
  product_data[i]["product" + i] = "test";
  product_data[i]["quantity" + i] = 2;
  product_data[i]["price" + i] = 99.99;
  product_data[i]["rem" + i] = "";
  product_data[i]["fpa" + i] = "xxx";  
}

console.log(product_data);