简体   繁体   English

如何遍历这种javascript对象?

[英]How do i loop throught this kind of javascript object?

Hello i just want to know how to iterate this array 您好,我只想知道如何迭代此数组

``` ```

[
        {
            "0": {
                "player_id": "138",
                "player_name": "Pring",
                "profile_image": "",
                "score_card": [
                    "0"
                ],
                "total_score": 22
            },
            "1": {
                "player_id": "4",
                "player_name": "Poring 12",
                "profile_image": "",
                "score_card": [
                    "0",
                ],
                "total_score": 0
            },
            "date": "2017-09-21",
            "start_time": "17:40:00",
            "end_time": "18:00:00"
        }
]

``` ```

or maybe group by players with lodash? 还是与lodash按玩家分组? im requesting to an api, but it seems that is not a cool one, or maybe im not good enough to perform this kind of arrays, (is my head hurt) 我正在请求一个api,但似乎不是很酷,或者可能不够好来执行这种数组(我的头部受伤了)

If you want to loop through objects in an array, you can do this 如果要遍历数组中的对象,可以执行此操作

for(var i=0; i<your_array.length; i++){
    var object = your_array[i]
    //your code here
}

If you want to loop through properties in an object, you can do this 如果要遍历对象中的属性,可以执行此操作

for(var propName in object){
    var prop = object[propName]
    //Your code here
}

If you only want to loop through properties with numeric format name, you can do this 如果只想遍历具有数字格式名称的属性,则可以执行此操作

for(var propName in object){
    if(!isNaN(propName)){
        var prop = object[propName]
        //Your code here
    }
}

Altogether, 共,

for(var i=0; i<your_array.length; i++){
    var object = your_array[i];
    console.log("From " + object.start_time + " to " + object.end_time);

    for(var propName in object){
        if(!isNaN(propName)){
            var playerIndex = propName;
            var player = object[propName]

            console.log("Index = " + playerIndex + ", ID = " + player.player_id + ", Name = " + player.player_name);

        }

    }
}

Output 输出量

From 17:40:00 to 18:00:00
Index = 0, ID = 138, Name = Jay Patoliya
From 17:00:00 to 18:00:00
Index = 0, ID = 138, Name = Jay Patoliya
From 17:40:00 to 18:00:00
Index = 0, ID = 138, Name = Jay Patoliya
Index = 1, ID = 4, Name = Jay Patoliya
Index = 2, ID = 49, Name = John DiFulvio

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM