Home > Blockchain >  How can I use substr on json object with for loop?
How can I use substr on json object with for loop?

Time:01-29

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]}`)
      }
    }

CodePudding user response:

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:

const data = [
    [
        "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"
    ]
]

const result = data.map(lines => lines.slice(1, -1).map(line => line.match(/(\$[0-9.] )(\w )(\$\d \.\d{2})(.*)/).slice(1)))
console.log(result)

  • Related