How to access an item in an array of objects? [closed]

2

I'm getting information from the database and putting it in an array: (more details of the code)

var alunos = {};
var self = 0;

function sortearAluno(){

    var dataForm = {'tipo': "listar"};
    $.ajax({
        type:'post',
        data: dataForm,
        dataType: 'json',
        url: 'alunoDAO.php',
        success: function(dados){
            var alunos = {};
            for(var i=0;dados.length>i;i++){
                        self++;
                        alunos['a'+self] = {            
                            idAluno : dados[i].idAluno,
                            nome: dados[i].nome,
                            classe : dados[i].classe,
                            hp : dados[i].hp,
                            ap : dados[i].ap,
                            xp : dados[i].xp,
                        }; 
            }
        }
    });
}

So far as normal, when I run the code it can create.

Chrome Console:

Butthen,whenItrytogetthevaluesofthekeys,Icannot.I'vetrieditinmanyways,I'vesearchedeverypagethatgoogleshowedme,butIdidnotfindanythingthatworked.

Someofmyattempts:

console.log(alunos.a1)

Displays="undefined"

console.log(alunos[a1].nome)

Displays="Uncaught ReferenceError: a1 is not defined"

Among other things I've tried. So, does anyone know how to solve this or have some better way to do this?

    
asked by anonymous 18.09.2016 / 10:14

1 answer

1

Try the following:

var dados = [
{
    idAluno : "1",
    nome: "Pedro",
    classe : "A1",
    hp : "3",
    ap : "5",
    xp : "1"
}, {
    idAluno : "1",
    nome: "Carlos",
    classe : "A1",
    hp : "8",
    ap : "7",
    xp : "1"
}, {
    idAluno : "3",
    nome: "José",
    classe : "A1",
    hp : "3",
    ap : "3",
    xp : "8"
}
]

var alunos = {};

for(var i=0;dados.length>i;i++){
var key = 'a' + String(i);

alunos[key] = {
    idAluno : dados[i].idAluno,
    nome: dados[i].nome,
    classe : dados[i].classe,
    hp : dados[i].hp,
    ap : dados[i].ap,
    xp : dados[i].xp,
};
}

document.write(alunos['a1'].nome)
    
18.09.2016 / 22:54