Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

157
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda