• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

181
Vistas
No se puede acceder a las propiedades del objeto por el argumento de una función

¿Por qué array[i].key (donde key === "apellido") dentro de la función no funciona, mientras que array[i].surname funciona perfectamente?

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

almost 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Tienes que acceder a la propiedad entre corchetes:

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

Este

 array[i].key

es equivalente a

 array[i]['key']
almost 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda