简体   繁体   中英

Updating an nested array of object in setState

I have an array with multiple array which holds multiple objects and i want to update any values in the object. I am able to update the object but my problem is whenever I update any object inside the array that parent array becomes object. I dont want to change the array to object. I am sharing my code and the output and expected output.

this.setState({
        tempArray: {
            ...this.state.tempArray,
            [lineNo]: {
                ...this.state.tempArray[lineNo],
                [pointNo]: {
                  ...this.state.tempArray[lineNo][pointNo],
                  x:parseInt(x),
                  y:parseInt(y)
                }
            }
          }
      },
      ()=>{
        console.log('callback tempArray',this.state.tempArray);
      })

If I change the first array x:7 to x:10 in the given array

[[{x:7,y:20}],[{x:50,y:60}],[{x:30,y:40}]]

My output is

[{x:10,y:20},[{x:50,y:60}],[{x:30,y:40}]]

But my expected output is

[[{x:10,y:20}],[{x:50,y:60}],[{x:30,y:40}]]

You're setting [lineNo] to an object. Try it like this:

tempArray: {
  ...this.state.tempArray,
  [lineNo]: [ // <--- [ instead of {
    ...this.state.tempArray[lineNo],
    [pointNo]: {
      ...this.state.tempArray[lineNo][pointNo],
      x:parseInt(x),
      y:parseInt(y)
    }
  ]// <--- ] instead of }
}

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