JoeBlack JoeBlack - 6 months ago 9
Javascript Question

How to dynamically create parameters' names

I have the following function that I want to make more generic:

function addRow2(rowData) {
var row = $("<tr />")
$("#dataTable").append(row);
row.append($("<td>" + rowData.param1 + "</td>"));
row.append($("<td>" + rowData.param2 + "</td>"));
row.append($("<td>" + rowData.param3 + "</td>"));
}


I tried the following approach:

function addRow1(rowData) {
var row = $("<tr />")
$("#dataTable").append(row);
for (i = 1; i <= 3; i++) {
var marker = [];
marker[i] = 'rowData.param'+i;
alert(marker[i]);
row.append($("<td>" + marker[i] + "</td>"));
}
}


However, instead of the values of
rowData.param1
...
3
it prints "rowData.param1", "rowData.param1" and "rowData.param1".

Answer

You can use bracket notation to access an object property by string name like this:

marker[i] = rowData['param' + i];

As a side note, you are creating a new array each iteration and storing your property name as the ith element of that array. You could more simply use a variable:

for (i = 1; i <= 3; i++) {
    var marker = rowData['param' + i];
    alert(marker);
    row.append($("<td>" + marker + "</td>"));
}

Or a one-liner:

for (i = 1; i <= 3; i++) {
    row.append($("<td>" + rowData['param' + i] + "</td>"));
}
Comments