Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple nested spread operators inside of an array (javascript es2015)

I'm working with a reducer using the React / Redux architecture. It's not specifically relevant to my question, as this is more of an ES2015 question. I have the following code:

return objectAssign({}, state, {
        sendingRequest: false,
        currentModel: {
            ...state.currentModel,
            components: [
                ...state.currentModel.components,
                0: {
                    ...state.currentModel.components[0], // can't do this, why?
                    selectedComponentGroup: {
                        ...state.currentModel.components[0].selectedComponentGroup,
                        availableComponents: action.payload.data
                    }
                }
            ]
        }
    });

However, ESLint is throwing an error:

✘  http://eslint.org/docs/rules/  Parsing error: Unexpected token  
C:\...\ProjectModelsReducer.js:122:25
...state.currentModel.components[action.componentIndex],

It's complaining specifically about the spread operator for this line:

...state.currentModel.components[action.componentIndex]

I can't figure out why this doesn't work and I was wondering if someone could shed some light into why the spread operator can't be used here.

like image 372
po3t Avatar asked Jun 08 '26 20:06

po3t


1 Answers

components: [
    ...state.currentModel.components,
    0: {
        // ...
    }
]

is not valid, just like [0: {}] is not valid as an array declaration. If you want to create a new array with a specific item changed, you'd have to use spread along with normal array syntax, or clone the array and mutate the index later, e.g.

components: [
    {
        // ...
    },
    ...state.currentModel.components.slice(1),
]

to create a new array with the first item replaced, or do

components: Object.assign([...state.currentModel.components], {
    0: {
        // ...
    }
}),

to clone the array then change the item at the 0 index.

like image 143
loganfsmyth Avatar answered Jun 10 '26 10:06

loganfsmyth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!