如何使用扩展运算符保留对象其余属性仅修改嵌套对象指定属性?
修改嵌套对象属性的扩展运算符用法
嘿,你问的这个嵌套对象修改问题其实很常见,用扩展运算符完全可以搞定,关键是要逐层展开复制,而不是只处理外层。我给你一步步拆解:
首先先看你原来的state对象:
let state = { authenticationObj: { "isAuthenticating": true, "isAuthentic": false, "subscriberId": "NA", "username": "NA", "firstName": "NA", "lastName": "NA", "enabled": "1", "email": "NA", isAuthorized: false }, lastPasswordCheckStatus: undefined }
要只修改authenticationObj里的email属性,同时保留其他所有属性(包括外层的lastPasswordCheckStatus和authenticationObj里的其他字段),你需要这样写:
// 定义新的email值 const newEmail = "user@example.com"; // 生成修改后的新state对象 const newState = { // 先复制外层对象的所有属性,保证外层其他属性不受影响 ...state, // 单独处理嵌套的authenticationObj:先复制它的原有属性,再覆盖email authenticationObj: { ...state.authenticationObj, email: newEmail } };
逻辑拆解
...state:把外层对象的所有属性(authenticationObj和lastPasswordCheckStatus)完整复制到新对象里,确保外层其他属性不会丢失或被误改。- 重新定义
authenticationObj时,...state.authenticationObj会先把原对象里的所有嵌套属性都复制过来,之后再单独指定email的新值,这样就只会替换目标属性,其他嵌套字段(比如isAuthenticating、username)都会保留原来的取值。
如果之后需要修改其他嵌套属性,也是同样的思路:逐层用扩展运算符复制原有属性,最后覆盖目标属性即可。
内容的提问来源于stack exchange,提问作者Hamed Minaee
相关产品推荐
相关产品推荐

