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

83
Vistas
How do I update array inside object in redux

I have an array I'm writing a code for redux now.

const initialState = [{ id: '1', title: '', description: '' }];

I would like to update that array like this

[{ id: '1', title: '', description: '' },{ id: '2', title: '', description: '' }];

and after copying I want to update the copy one of id to '2'

here is what I tried

    case COPY_QUESTION: {
      const copyQuestion = state.find(question => question.id === action.payload)
      copyQuestion?.id = (state.length + 1).toString()
      return [...state, copyQuestion];
    }

it didn't work for me. if I try to change id, the 0 index changes too at the same time. like this

[{ id: '2', title: '', description: '' },{ id: '2', title: '', description: '' }];

I would really appreciate your help thanks for reading this question.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Something like this should work:

const initialState = [{ id: '1', title: '', description: '' }];

const copyInitialState = [...initialState]

copyInitialState.push({ id: parseInt(copyInitialState[copyInitialState.length - 1].id, 10) + 1, title: '', description: '' })

//setState

copyInitialState is then equal to:

[
 {
  id:"1",
  title:"",
  description:""
 },
 {
  id:2,
  title:"",
  description:""
 }
]
about 4 years ago · Juan Pablo Isaza Denunciar

0

JavaScript handels Objects by reference and therefore ’find’ only returns the address in memory of the already existing object, which you then manipulate.

You have to clone your object first, e.g. using the spread operator (not for deep clones):

const originalQuestion = state.find(question => question.id === action.payload)
const copyQuestion = { ...originalQuestion }

Have a look at this SO question for more context and possibilities.

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