How to use function parameter as object attribute?

Asked

Viewed 60 times

0

Hello!

In order to reuse a function I am performing the following procedure:

View 1 has this obj:

  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 did 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 by passing the obj, the name of the title attribute and the name of the value attribute, because both vary according to the obj.

Expected result:

At the end of everything, whenever I call the transforms function it will return to min an array of objects with title and value, contained in the date

  • But the parameters of tranforma are to apply to all elements of the data ? Or just the one ? In my optics it would be easier to exemplify with the result you expect obj2 at the end of map run.

  • Change item."AQUI SERA O QUE VIER EM TITULO" for item[titulo], that’s it? push is a function for array, you are trying to call it in an object, it will not work

  • You’re right, I rephrased the question

  • William solved item[title]

1 answer

1


The use of square brackets ([ ]) to access variables had already been answered here on the site (if I am 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, it could simply do:

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

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

Browser other questions tagged

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