【问题标题】:How can I use substr on json object with for loop?如何在带有 for 循环的 json 对象上使用 substr?
【发布时间】:2023-01-28 22:04:34
【问题描述】:

有人可以帮助了解如何在使用 substr 获取每个变量时循环响应。变量将是金额、类型、余额、日期。

我有 json 响应

[
    [
        "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"
    ]
]

这是我的代码

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

【问题讨论】:

  • 为什么您的服务器不发送具有适当属性(如{Amount: "", Type: "", Balance: "", Date: ""})的 json 响应,这应该是您修复它的地方,而不是像您描述的那样处理它

标签: javascript json for-loop substr text-parsing


【解决方案1】:

如果您的字段长度不同(“借方”与“贷方”),您不能使用substr(),至少不是没有麻烦(即尝试值直到一个匹配)。

你可以使用正则表达式:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    • 2020-05-31
    • 2016-11-18
    相关资源
    最近更新 更多