【问题标题】:How to get string from API depending on another string in same section?如何根据同一部分中的另一个字符串从 API 获取字符串?
【发布时间】:2017-03-25 21:12:41
【问题描述】:

(对不起,如果标题没有多大意义,我不知道如何正确表达问题,这是我能想到的最佳方式)

所以我有一个 API(steam API),它返回如下内容:

   {
        "playerstats": {
            "steamID": "76561197962837077",
            "gameName": "ValveTestApp260",
                "stats": [
                    {
                        "name": "total_kills",
                        "value": 3255
                    },
                    {
                        "name": "total_deaths",
                        "value": 4816
                    },
                    ...
                    {
                        "name": "total_shots_hit",
                        "value": 3642
                    }
                    {
                        "name": "total_shots_fired",
                        "value": 4572
                    }
                    ...
                ],
        }
}

所以我想获得total_shots_hittotal_shots_fired 的值,但是对于不同的人来说它的顺序不同,所以我想知道如何根据每个部分中的名称获得值?我现在做的方式是做statsResponse.playerstats.stats[39].value,但它不是每个人都排在第39位,所以我想知道我怎么会得到它?如果有帮助的话,我正在使用 JavaScript/jQuery。

任何帮助表示赞赏:)

编辑:想出了怎么做,我使用 for 循环遍历每个响应,直到找到我想要的项目,然后使用该数字找到相同的值

【问题讨论】:

    标签: javascript jquery json api


    【解决方案1】:

    您可以使用Array.find() 通过其属性之一在数组中查找对象。

    var o = stats.find(function(item) {
        return item.name === 'total_shots_hit';
    }
    
    console.log(o.value) // value property, e.g. 3642
    

    【讨论】:

    • 每当我尝试它给我一个错误说Uncaught TypeError: Cannot read property 'value' of undefined at XMLHttpRequest.statsRequest.onreadystatechange时,我尝试将它转换为一个数组,因为它的Array.find(),但它只是给我一个console.log(o.value)的错误,如果我这样做console.log(o),它只会说undefined
    • @ConnorS 也许查看更多代码会有所帮助,因为我提供的内容在我的测试中肯定有效。我不知道 XMLHttpRequest 是怎么出现的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 2023-03-16
    • 2012-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多