简体   繁体   中英

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

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
  )
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM