Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

116
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!