javascriptreactjsreduxspread-syntax

Returning mutated object with some key modified using spread operator


In the below object, I want to increment the value of data[1]'s val by 1, and leave everything unchanged, how can I achieve it?

const state = 
    {
        "data": [{
                "val": 1,
                "other": 10
            },
            {
                "val": 11,
                "other": 100
            },
            {
                "val": 100,
                "other": 1000
            }
        ]
    }

I want the mutated object to be like this-

{
    "data": [{
            "val": 1,
            "other": 10
        },
        {
            "val": 10,
            "other": 100
        },
        {
            "val": 100,
            "other": 1000
        }
    ]
}

I know that I can change the value directly like this- state.data[1].val = state.data[1].val+1, but I want to achieve the same using spread operator, is it possible to achieve it using spread operator? Somthing like this-

const mutatedState = {
        ...state,
        data: [...state.data]
}

Solution

  • Get the data out of the object. And use like this

    const state = { "data": [{ "val": 1, "other": 10 }, { "val": 11, "other": 100 }, { "val": 100, "other": 1000 } ] }
        
    const {data} = state;         
    let res = {
                ...state,
                data:[
                        data[0],
                        {...data[1],val:data[1].val+ 1},
                        ...data.slice(2)
                     ]
              }
     
    console.log(result)