How to use function parameter as an attribute of an object?

0

Hello!

In order to reuse a function I'm doing the following:

View 1 has this object:

  obj: [
  {"fruta": "maça", "valor1":1},
  {"fruta": "banana", "valor1":1},
  {"fruta": "pera", "valor1":1}
  ]

View 2 has this object:

obj: [
  {"trufa": "chocolate", "preço":1},
  {"trufa": "doce de leite", "preço":1},
  {"trufa": "nutela", "preço":1}
  ]

View 3 has this:

  obj: [
      {"carro": "uno", "avaliado":12222},
      {"carro": "gol", "avaliado":133333},
      {"carro": "jetta", "avaliado":133333}
      ]

I've done a function that transforms these objects:

function tranforma(data, titulo, id){

let obj1 = {}
let obj2 = []

data.map(item => {
 //aqui esta meu erro, preciso fazer isso, mas nao sei como:
 obj1.titulo = item."AQUI SERA O QUE VIER EM TITULO"
 obj1.value = item."AQUI SERA O QUE VIER EM ID"

 obj2.push(obj1);
});

return obj2;

}

In the views I call the function passing the obj, the name of the title attribute and the name of the value attribute, since both vary according to the obj.

Expected result:

At the end of it all, whenever I call the function turns it will return an object array with a title and value contained in the data to min

    
asked by anonymous 10.10.2018 / 18:09

1 answer

1

The use of brackets ( [ ] ) to access variables had already been answered here on the site (if I'm not mistaken I answered myself), but I did not find the question to link, as for your code, some tips:

  • Creating a "temporary" variable to create an object is unnecessary, you could simply do:

    obj2.push({
        titulo: item[titulo],
        value: item[id]
    });
    
  • If you are using map you can change its values and return the result of the function:

    function tranforma(data, titulo, id){
        return data.map(item => {
            return {
                titulo: item[titulo],
                value: item[id]
            }
        });
    }
    
10.10.2018 / 19:47