-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.

3

2 Answers 2

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++;
}
Sign up to request clarification or add additional context in comments.

Comments

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++;
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.