Doubt about Map/javascript

Asked

Viewed 59 times

1

I have one question: I need to use the Map function to swap the values of the objects, for example: Start([{name:Rui, sex:"m" ; name:Ana, sex:"f"}]) How do I change the sex of people, say that Rui is f and Ana is m? inserir a descrição da imagem aqui

  • Can you explain the logic better? Do you always have 2 people who switch between you? or how do you know what value to change?

  • Thanks for the answer. I just have to change the value of the person’s gender, reverse what I have within the array. Say the boy is feminine and the girl is masculine.

1 answer

4

Your starting point is an Array: [{name: 'Rui', sex: "m"}, {name: 'Ana', sex: "f"}];. The .map() traverse each element (2 in this example) and lay out the iterated object. Then you only need logic to swap the value...

const arr = [{
  name: 'Rui',
  sex: "m"
}, {
  name: 'Ana',
  sex: "f"
}];
const invert = sex => sex === 'm' ? 'f' : 'm';
const trocado = arr.map(obj => {
  return {
    ...obj,
    sex: invert(obj.sex)
  }
});

console.log(trocado);

Browser other questions tagged

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