Game Table Creation

5

I wrote this code to organize the teams that will face in the Cup:

<script>
var dados = {
    "grupo1" : [
        {"selecao" : [{"nome":"brasil"},{"resultado" : [{"a":0},{"a":4},{"a":2}]}]},
        {"selecao" : [{"nome":"croacia"},{"resultado" : [{"a":0},{"a":4},{"a":2}]}]},
        {"selecao" : [{"nome":"camaroes"},{"resultado" : [{"a":0},{"a":4},{"a":2}]}]},
        {"selecao" : [{"nome":"mexico"},{"resultado" : [{"a":0},{"a":4},{"a":2}]}]}
    ],
};

var jsonData = eval(dados);

alert(jsonData.grupo1[0].selecao[0].nome);

document.write(jsonData.grupo1[0].selecao[0].nome+" x "+jsonData.grupo1[1].selecao[0].nome+"<br />");
document.write(jsonData.grupo1[3].selecao[0].nome+" x "+jsonData.grupo1[2].selecao[0].nome+"<br />");
document.write(jsonData.grupo1[0].selecao[0].nome+" x "+jsonData.grupo1[3].selecao[0].nome+"<br />");
document.write(jsonData.grupo1[2].selecao[0].nome+" x "+jsonData.grupo1[1].selecao[0].nome+"<br />");
document.write(jsonData.grupo1[1].selecao[0].nome+" x "+jsonData.grupo1[3].selecao[0].nome+"<br />");
document.write(jsonData.grupo1[2].selecao[0].nome+" x "+jsonData.grupo1[0].selecao[0].nome+"<br />");

However, since there are multiple groups, if you continue to organize them in this way will result in a very large code, would you like to know if there is a better way to do it?

    
asked by anonymous 02.03.2014 / 07:48

1 answer

4

You can organize the data in a different way, this will depend on them and how you will present them. An example is to put them in a Array , to facilitate access to different groups.

var dados = [
    [
        {"selecao": [{"nome":"brasil"},  {"resultado": [{"a":0},{"a":4},{"a":2}]}]},
        {"selecao": [{"nome":"croacia"}, {"resultado": [{"a":0},{"a":4},{"a":2}]}]},
        {"selecao": [{"nome":"camaroes"},{"resultado": [{"a":0},{"a":4},{"a":2}]}]},
        {"selecao": [{"nome":"mexico"},  {"resultado": [{"a":0},{"a":4},{"a":2}]}]}
    ] /* , [grupo 2, etc] */
];

eval was not required and alert suppose it would be for testing.

Now, let's create a variable to organize the games: in this case I used an Array that contains the games, which can be organized in [selecao-1, selecao-2] or objects:

var jogos = [[0, 1], [3, 2], [0, 3], /* ... */];

So let's show the data:

document.write(jogos.map(function (times) {
  return dados[0][times[0]].selecao[0].nome + " x " + dados[0][times[1]].selecao[0].nome;
}).join('<br>'));

If you are going to use a library or if the data needs to be shown otherwise, you can change that last block of code to fit it.

Also, depending on the way you organized HTML, you can stop using document.write and use functions like .appendChild and .insertBefore , preventing HTML from being reprocessed, which makes it faster.

/ p>     

02.03.2014 / 13:44