Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

52
Vistas
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');

7 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

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']
7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos