Object change with javascript

Asked

Viewed 40 times

1

My API is returning a array with the objects in the following structure:

[
  {id: 1, name: "Flávio", position: "SP - Atacante"},
  {id: 2, name: "João", position: "SP - Goleiro"},
  {id: 3, name: "Fernando", position: "RJ - Zagueiro"},
  {id: 5, name: "Robert", position: "SP - Todas"},
];

I need to take this guy’s last position (object with position: 'SP - Todas') and remove SP text - leaving only "All".

I tried it this way and it worked (should not be the best way, if you have suggestions, thank you).

jogadores.map((jogador, i) => {
    if (jogador.position.includes('Todas')) {
    console.log(jogador.position.substr(4));
  };
});

The problem is that I need to return the array with this last edited object, but I’m not sure how to do it.

Jsfiddle example

  • You want to remove the SP in the "last position" or in the one that has the text "All"? in the example is the same, but it is always the same?

1 answer

2


To solve this problem, just use the split function, the result of this operation is an array in which:

  1. at zero position will be the value "SP "
  2. in position one will be the value " Todas"

So just remove the whitespace to the one position of the array [calling the function trim()].

const jogadores = [
    {id: 1, name: "Flávio", position: "SP - Atacante"},
    {id: 2, name: "João", position: "SP - Goleiro"},
    {id: 3, name: "Fernando", position: "RJ - Zagueiro"},
    {id: 5, name: "Robert", position: "SP - Todas"},
]

const j = jogadores.map((jogador) => {
    if (jogador.position.includes('Todas')) {
      jogador.position = jogador.position.split('-')[1].trim();
      return jogador;
    }
    return jogador;
})
  • Are you using the .map to change the initial array... you should use the return map to generate an altered array and not change the initial array.

  • Thank you for reporting the error. I have corrected.

Browser other questions tagged

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