-1

How to generate the variable and assign inside for loop dynamically?

For Example,,

var tempClosingBalance, k = 1;
for (var i = 0; i < customArray.length; i++) {
    tempClosingBalance = "ClosingBalanceWithType" + k;
    for (var j = 0; j < output.length; j++) {
        output[j].tempClosingBalance = customArray[i][j].ClosingBalanceWithType;
    }
    k++;
}

Here tempClosingBalance variable have ClosingBalanceWithType1 and assign value, Same condition continued assign value in ClosingBalanceWithType2, ClosingBalanceWithType3, etc.

rrk
  • 15,677
  • 4
  • 29
  • 45
Vignesh
  • 1
  • 1
  • Possible duplicate of [javascript object variable key](http://stackoverflow.com/questions/6071471/javascript-object-variable-key) – T J Jan 29 '16 at 05:30
  • this has nothing to do with jQuery – T J Jan 29 '16 at 05:30
  • Possible duplicate of [Using a variable for a key in a JavaScript object literal](http://stackoverflow.com/questions/2274242/using-a-variable-for-a-key-in-a-javascript-object-literal) – rrk Jan 29 '16 at 05:39

2 Answers2

0

I think the following will work. The direct . operator will not work here.

Use output[j]["ClosingBalanceWithType" + k].

var tempClosingBalance, k = 1;
for (var i = 0; i < customArray.length; i++) {
    tempClosingBalance = "ClosingBalanceWithType" + k;
    for (var j = 0; j < output.length; j++) {
        output[j][tempClosingBalance] = customArray[i][j].ClosingBalanceWithType;
    }
    k++;
}
rrk
  • 15,677
  • 4
  • 29
  • 45
0
for (var i = 0; i < customArray.length; i++) {
            for (var j = 0; j < output.length; j++) {
                output[j]["ClosingBalanceWithType" + k] = customArray[i][j].ClosingBalanceWithType;
                output[j]["TransactionCount" + k] = customArray[i][j].TransactionCount ? customArray[i][j].TransactionCount : 0;
                output[j]["AmountType" + k] = customArray[i][j].AmountType;
            }
            k++;
        }
Vignesh
  • 1
  • 1