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