Use parameter passed in function within map()

Asked

Viewed 32 times

1

My job:

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
  • 3

    Try it this way list.map( user => user.id == id ? name = user[getter] : null);

  • 1

    It worked, vlw!!! I didn’t know it was possible to do this.

1 answer

1


When passing a variable to select a property in 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 won’t work because we’re looking for a property called key specifically, and not the contents of the variable key. For that 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"
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.