How to access an item in an object array?

Asked

Viewed 6,137 times

2

I’m taking information from the database and putting it into 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 it’s normal, when I run the code it can create.

Console in Chrome:

inserir a descrição da imagem aqui

But then, when I try to get the Keys' values, I can’t. I’ve tried several ways, I’ve searched every page that google showed me, but I can’t find anything that works.

Some of my attempts:

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 has some better way to do it?

  • 2

    What appears with console(alunos['a1'].nome)?

  • 3

    Are you creating this object inside the ajax callback and using it outside of it? You can show more code and an example of the content of dados?

  • @Victorstafusa For your information, index an object with . is the same as indexing an object computed with [...], the difference is that with the . you can only declare a valid Ecmascript identifier, so the same as indexing an object with a String. That is, there will be almost the same mistake if you try to make an expression like alunos['a1'].nome instead of alunos[a1].nome, the error will be different because you are declaring a String in indexing, for example: Uncaught TypeError: Cannot read property 'nome' of undefined

  • Victor, aparece " Uncaught Typeerror: Cannot read Property 'nomeP' of Undefined".

  • Sergio, update the post with more parts of the code

  • And people tried to do what Victor said inside the ajax callback as Sergio commented and it worked. I figured because I declared the students out of office and added the data and then using that same variable would work, but it doesn’t look like it. Thank you!

Show 1 more comment

1 answer

2


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)

  • Hello Emir Marques had already succeeded, that’s right, what was going wrong in mine is that I was trying to use the variable outside the ajax method, I imagined that by creating it outside the method, and adding the values inside the ajax method, in any other method I would have access, but it seems not, I just do everything in the same method that works, but still thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.