Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use object spread with nested properties?

Tags:

I'm trying to return the following in my reducer (react-redux) and it's giving me a syntax error:

return { ...state, loginForm.email: action.payload.email }  state = { loginForm: { email: '', password: '' } } so on 

I have babel preset stage 0 installed and es2015. This works fine:

return { ..state, loginForm: action.payload } 
like image 811
Marina Dunst Avatar asked Nov 03 '17 19:11

Marina Dunst


People also ask

Does spread operator work on nested objects?

The spread operator only creates a new address location for the top-level elements. Any nested objects of newObject are still at the same address locations as the nested objects of object . This means that we need to apply the spread operator at every level we want make a true value copy.

Can I use spread for object?

Spread syntax can be used when all elements from an object or array need to be included in a new array or object, or should be applied one-by-one in a function call's arguments list.

How do I access nested objects?

The sub-properties of objects can be accessed by chaining together the dot or bracket notation .


1 Answers

Error you are getting because of the this key:

loginForm.email 

It's not a valid object key.

Write it like this:

return {      ...state,      loginForm: {         ...state.loginForm,         email: action.payload.email     }  } 
like image 128
Mayank Shukla Avatar answered Oct 06 '22 01:10

Mayank Shukla