我如何循环JSON文件?

时间:2018-05-05 13:47:24

标签: javascript

我有一个JSON文件:

{
    "stats": {
        "operators": {
            "recruit1": {
                "won": 100,
                "lost": 50,
                "timePlayed": 1000
            },
            "recruit2": {
                "won": 200,
                "lost": 100,
                "timePlayed": 2000
            },
            "recruit3": {
                "won": 50,
                "lost": 10,
                "timePlayed": 500
            }
        },
        "modes": {
            "secure": {
                "won": 80,
                "lost": 40,
                "bestScore": 7582
            },
            "bomb": {
                "won": 12,
                "lost": 18,
                "bestScore": 4500
            }
        }
    }
}

我想在表格中显示它: like this

我试图在循环中使用但是我的名字没有它们的值。

1 个答案:

答案 0 :(得分:0)

以下是如何开始:

var obj = {
"stats": {
    "operators": {
        "recruit1": {
            "won": 100,
            "lost": 50,
            "timePlayed": 1000
        },
        "recruit2": {
            "won": 200,
            "lost": 100,
            "timePlayed": 2000
        },
        "recruit3": {
            "won": 50,
            "lost": 10,
            "timePlayed": 500
        }
    },
    "modes": {
        "secure": {
            "won": 80,
            "lost": 40,
            "bestScore": 7582
        },
        "bomb": {
            "won": 12,
            "lost": 18,
            "bestScore": 4500
        }
    }
}
}

for(var k in obj.stats){
  console.log('-',k)
  for(var k2 in obj.stats[k]){
    console.log('-----',k2)
    for(var k3 in obj.stats[k][k2]){
      console.log('---------',k3 +': '+ obj.stats[k][k2][k3]);
    }
  };
}