Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

287
Visualizações
Can't access object's properties by argument of a function

Why array[i].key (where key === "surname") within the function doesn't work, meanwhile array[i].surname works perfectly?

let objects = [
    { name: 'Jack', surname: 'Jackson' },
    { name: 'Ivar', surname: 'Bjornsson' },
    { name: 'John', surname: 'Mickelson' }
];

function sort (array, key) {
    for (let i = 0; i < array.length; i++) {
        console.log(array[i].key)// Somehow the "key", which is equal to "surname" doesn't work;
        // here will be undefined;
        console.log(array[i].surname)//But here writing 'surname' directly works fine;
        // the correct answer will be there;
        console.log(key)// However, key === surname
    }
}

sort(objects, 'surname');

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You have to access the property with square brackets:

let objects = [
    { name: 'Jack', surname: 'Jackson' },
    { name: 'Ivar', surname: 'Bjornsson' },
    { name: 'John', surname: 'Mickelson' }
];

function sort (array, key) {
    for (let i = 0; i < array.length; i++) {
        console.log(array[i][key])// Somehow the "key", which is equal to "surname" doesn't work;
        // here will be undefined;
        console.log(array[i].surname)//But here writing 'surname' directly works fine;
        // the correct answer will be there;
        console.log(key)// However, key === surname
    }
}

sort(objects, 'surname');

This

array[i].key

is equivalent to

array[i]['key']
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda