Basic Doubt Javascript: How to change an object attribute?

Asked

Viewed 1,821 times

4

I ended up facing a slightly different situation and I was in doubt.

I would like to know the following, I have an array of objects and in each object I have two attributes in it {valor: "texto", tamanho: "médio" }.

I would like to create a new array using map for example and I would like that in my new array I change the name of the attribute size to measure.

How do I create this new array but instead of the attributes of each object being (value and size) they are (value and measure) ?

  • Put the code of what you’ve already done, so we can help you better.

  • How do I put the code here ? in the comment it did not let pq exceeded the amount of characters.

  • Use the edit button. Also, select the code and click the button that has a key opening and a closing to format the code.

3 answers

5

You can do that with the .map as you mentioned. The code would look like this:

const lista = [{
  valor: "azul",
  tamanho: "grande"
}, {
  valor: "verde",
  tamanho: "pequeno"
}, {
  valor: "branco",
  tamanho: "medio"
}];

function usarMedida(arr) {
  return arr.map(obj => {
    return {
      valor: obj.valor,
      medida: obj.tamanho
    };
  });
}

console.log(usarMedida(lista));

If the object is more complex than the one you have in question you can do so:

const lista = [{
  valor: "azul",
  tamanho: "grande"
}, {
  valor: "verde",
  tamanho: "pequeno"
}, {
  valor: "branco",
  tamanho: "medio"
}];

function usarMedida(arr) {
  return arr.map(entry => {
    return Object.keys(entry).reduce((obj, key) => {
      const value = entry[key]; // ler o valor
      if (key === 'tamanho') key = 'medida'; // mudar o nome da chave
      obj[key] = value;
      return obj;
    }, {});
  });
}

console.log(usarMedida(lista));

3

To accomplish this "change", you can create a new attribute and remove the old one.

Thus:

lista = [ {valor: "azul", tamanho: "grande"}, {valor: "verde", tamanho: "pequeno"}, {valor: "branco", tamanho: "medio"} ];

lista.forEach(function(value) {
    value.medida = value.tamanho;
    delete value.tamanho;
});

console.log( lista );
  • 1

    But this changes the original array, which does not match what the question indicates, "I would like to create a new array ..."

  • That’s enough for what I need to do !!! Thanks Valdeir !

0

You’re on the right track, the method map serves for you to access the indexes of an array and turn them into another value. In your case, the approach to do it is quite simple:

const lista = [ {valor: "azul", tamanho: "grande"}, {valor: "verde", tamanho: "pequeno"}, {valor: "branco", tamanho: "medio"} ]
const mapped = lista.map(({valor, tamanho}) => ({ valor, medida: tamanho }))

If you want to encapsulate this solution to reuse functionally:

// função que trasforma um determinado objeto
const sizeToMesure = ({valor, tamanho}) => ({ valor, medida: tamanho })

// curry function que recebe um mapper e retorna um map
const remapWith = mapper => src => src.map(mapper)

// cria um novo mapper a partir de uma function de transformação
const remapIn = remapWith(sizeToMesure)

// Ao executar este método em uma array, ele a trasforma em uma nova
remapIn(lista) // Array [{...},{...},...

Browser other questions tagged

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