Use parameter passed in function inside the map ()

1

My role:

nameById (url, list, getter = "name") {
    let name = '';
    let id = url.split('/').reverse()[1];
    list.map( user => user.id == id ? name = user.name : null); // name = user.getter
    return name;
},

Is there any way to use this getter parameter inside the map? That way I could use this function not only to search for "name" but for any other key.

nameById('http://localhost:8000/scrum-list/sprint-list/7/', sprintList, 'code') // O retorno seria a propriedade de code e não name
    
asked by anonymous 10.11.2017 / 14:44

1 answer

2

When passing a variable to select a property on an object, use obj[variavel] . Considering the following object:

obj = {
    nome: 'Lucas',
    idade: 24
}

If we use the following function:

function a(key = "nome"){
    console.log(obj.key)
}

It will not work because we are looking for a property called key specifically, not the content of the key variable. For this we can do:

function a(key = "nome"){
    // isso é mesmo que obj.nome
    console.log(obj[key]); // irá olhar para o conteúdo de key, nesse caso "nome"
}
    
10.11.2017 / 15:25