Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

156
Visualizações
how to use .filter to edit a state in react without mutating

Im not sure if this is even possible as I dont think .filter can be used for something like this. If I have an array like so:

abc: [
    {number: 1, letter: "a"},
    {number: 2, letter: "b"},
    {number: 3, letter: "c"},
    {number: 4, letter: "d"},
]

I want to do something like this

abc.filter(item => {
        if(item.number == 1){
            
            item.letter == "aa"
        }
    })

Basically updating the first element in the object to be {number:1, letter:"aa"}. However this ends up giving me an empty array. I dont think im going about it in the correct way. How could I use filter to make edits to certain elements?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

.filter is not really appropriate here because that would create a new array with only the elements fulfilling the condition, which would then have to be put back into the original array somehow - possible, but convoluted. Map the array instead - if the condition is fulfilled, return a changed object.

Remember that in React, you should avoid mutation - don't assign to a property of an existing object, create a new one instead.

const abc = [
    {number: 1, letter: "a"},
    {number: 2, letter: "b"},
    {number: 3, letter: "c"},
    {number: 4, letter: "d"},
];
const newArr = abc
  .map(obj =>
    obj.number === 1
    ? { ...obj, letter: 'aa' }
    : obj
  );
console.log(newArr);

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda