1

I have a JSON file:

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

And I want to display it in a table : like this.

I have tried to use for in loop but I only got names without their values.

alessandrio
  • 4,282
  • 2
  • 29
  • 40
  • 5
    Post the exact code you've tried. – Smuuf May 05 '18 at 13:48
  • You don't loop a JSON file, you loop an array. Same idea here, so look at how to do a `for each` in Javascript (hint: yes, you do need to use the key as the accessor within the loop). – Jared Farrish May 05 '18 at 13:50
  • People expect to see what you tried (your code), in a well formatted question. Help them help you. Please take the [**stack overflow tour**](http://stackoverflow.com/tour) to know more about this site, and read about **[how to ask](https://stackoverflow.com/help/how-to-ask)**. – YvesLeBorg May 05 '18 at 13:50
  • your code isn't there, but if you trying to display name as ".operators" then also try like ".operators.won", ".operators.lost"... – Muhammad Ali Hassan May 05 '18 at 13:52
  • use `each` with `stats` and output data as table structure you want but you have to show what you have done we will not write code for you. – Shiv Singh May 05 '18 at 13:54
  • `response.stats.operators[x]` to get the values – Cristian Tr May 05 '18 at 14:14

1 Answers1

0

Here is how you can start:

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]);
    }
  };
}
Mamun
  • 66,969
  • 9
  • 47
  • 59