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

121
Visualizações
Replace element in array with in one line using spread operator in javascript react

Im trying to set a new state but the only thing that is changing is an element in this array. I'm still very new to javascript so I don't really understand how to do the syntax.

I know that I can create a new object using the spread operator and can add/change something in the object if it's at the top level but how do I do for in an array

newRow = {
 name: "kevin"
 status: false
}

currentStageData = {
 name: "Stage 1"
 items: [
   {
    name: "david"
    status: true
},   
{
    name: "kevin"
    status: true
},
{
    name: "bruce"
    status: true
},
 ]
}

I tried to do doing this but this syntax doesn't work.

var newCurrentStageData = { ...currentStageData, newCurrentStageData.items[index]: newRow }

So I end up having to do this.

var newRow = { ...row, status: e.target.checked }
var newCurrentStageData = { ...currentStageData }

newCurrentStageData.items[index] = newRow
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Spreading won't work here because the index you want to insert the item to isn't necessarily at the end or beginning.

Your current approach is also violating React rules by mutating the state, which should never be done.

If the index is already present in the array, .map to create a new one, replacing the item at the same index when the condition is met.

const newCurrentStageData = { ...currentStageData, items: currentStageData.items.map((item, i) => i === index ? newRow : item) };

But I really wouldn't put it all on one line. Readability is more important than line compression.

const newCurrentStageData = {
  ...currentStageData,
  items: currentStageData.items.map(
    (item, i) => i === index ? newRow : item
  )
};
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