0

I have the following loop:

for( i = 1; i < parseInt(data.anzahl_parameter) + 1; i++ )
{
    newParameterInputFieldLabel = $( "<label>" )
    .text( data.p1_einheit )
        .attr( "for", "einheit1" )
        .appendTo( newInputAreaAmountDiv );


    newParameterInputField = $( "<input>" )
        .addClass("insertFloat")
        .attr("id", "einheit" + i)
        .appendTo( newParameterInputFieldLabel );
    }

The variable data.p1_einheit comes from a json-array. This works fine, when data.anzahl_parameter have only 1 Element.

But when i have 2 or more elements, then I couldn't use the variable dynamically.

I have tried this:

data.p[i]_einheit

but my script stops.

What should I change for make it working?

1 Answer 1

0

You have to put the entire property name (as a string) between the square brackets. Use them instead of dot-notation, not in the middle of it.

data["p" + i + _einheit]

You'd probably be better off refactoring the JSON so you have an array instead of properties following a numeric convention though.

Sign up to request clarification or add additional context in comments.

Comments