Could someone help on how to loop over response while using substr to get each variable. The variables would be Amount, Type, Balance, Date.
I have the json response
[
[
"AmountTypeBalanceDate",
"$27.90Debit$6.3011/22/22, 3:32 PM",
"$30.00Credit$34.2011/22/22, 5:13 PM",
"$27.90Debit$4.209/12/22, 4:01 PM",
"$30.00Credit$32.109/12/22, 8:49 PM",
"$27.90Debit$2.107/20/22, 10:23 AM",
"$30.00Credit$30.007/20/22, 3:22 PM",
"Balance: $200.30"
]
]
Here is my code
if (xhr.status == 200) {
console.log("status 200");
var parsedWalletResult = JSON.parse(this.response);
console.log(parsedWalletResult.values[0][2]); //Get the second value
// Get the amount from the second
var walletAmount = parsedWalletResult.values[0][2]
walletAmount = walletAmount.substr(0, 5);
console.log("The wallet amount is: " + walletAmount);// The wallet amount is: $30.0
// loop over the parsed json response
for (const key in parsedWalletResult){
if(parsedWalletResult.hasOwnProperty(key)){
console.log(`${key} : ${parsedWalletResult[key]}`)
}
}
2
Answers
You cannot use
substr()
if the length of your fields differ ("Debit" vs "Credit"), at least not without hassle (i.e. trying out values until one matches).You could use a regex though:
This is a perfect scenario for Regular Expressions. If you don’t know regex, be careful, as this will be hard to maintain.
Here’s my solution:
(possibly a more accurate regex than the other answer)