我如何循环这种javascript对象?

时间:2017-10-04 00:22:10

标签: javascript arrays loops

你好我只是想知道如何迭代这个数组

```

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

```

或者可能是由拥有lodash的玩家组成的?我要求api,但它似乎不是一个很酷的,或者我可能还不够好,不能执行这种阵列,(是我的头疼)

1 个答案:

答案 0 :(得分:2)

如果要循环遍历数组中的对象,可以执行此操作

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

如果要遍历对象中的属性,可以执行此操作

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

如果您只想循环使用数字格式名称的属性,则可以执行此操作

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

总之,

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);

        }

    }
}

输出

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