如何获取嵌套对象的键?嵌套字典更新stateCopy的实现方法
解决嵌套对象的键获取与状态更新问题
嘿,针对你提出的两个嵌套对象相关问题,我来一步步给你拆解解决方案:
1. 获取嵌套对象的所有键(含层级路径)
要拿到嵌套对象里的完整键路径,我们可以写个递归函数遍历每一层,把每个叶子节点的键路径用数组或字符串形式返回,方便后续操作。
举个递归实现的例子:
function getNestedKeys(obj, parentPath = []) { let keys = []; for (const [key, value] of Object.entries(obj)) { const currentPath = [...parentPath, key]; if (typeof value === 'object' && value !== null && !Array.isArray(value)) { // 遇到嵌套对象,继续递归深挖 keys = [...keys, ...getNestedKeys(value, currentPath)]; } else { // 非对象类型,记录完整路径(也可以转成字符串:currentPath.join('.')) keys.push(currentPath); } } return keys; } // 用你的示例dictionary测试 const dictionary = {left:{name:'WORK', min:2, sec:0}, start:true}; console.log(getNestedKeys(dictionary)); // 输出:[ ['left','name'], ['left','min'], ['left','sec'], ['start'] ]
2. 递归更新嵌套结构的stateCopy
原来的代码只处理扁平对象,遇到嵌套结构就失效了——因为stateCopy.key只会给stateCopy新增一个叫key的属性,而非动态设置对应的嵌套键。我们可以写个辅助函数来处理嵌套赋值,再结合递归遍历完成更新:
方法1:直接更新拷贝后的对象
这种方式适合不需要严格保持不可变性的场景,直接逐层赋值:
// 辅助函数:给目标对象设置嵌套属性 function setNestedProp(target, path, value) { let current = target; // 遍历路径的前n-1层,确保每层对象都存在 for (let i = 0; i < path.length - 1; i++) { const key = path[i]; if (!current[key]) { current[key] = {}; } current = current[key]; } // 设置最后一层的属性值(按需求转成字符串) current[path[path.length - 1]] = value.toString(); } // 主更新逻辑 const dictionary = {left:{name:'WORK', min:2, sec:0}, start:true}; let stateCopy = {...this.state}; // 先浅拷贝基础state // 递归遍历dictionary的所有键值对 function updateStateCopy(obj, parentPath = []) { for (const [key, value] of Object.entries(obj)) { const currentPath = [...parentPath, key]; if (typeof value === 'object' && value !== null && !Array.isArray(value)) { updateStateCopy(value, currentPath); } else { setNestedProp(stateCopy, currentPath, value); } } } updateStateCopy(dictionary); // 现在stateCopy就会满足:stateCopy.left.name='WORK'、stateCopy.left.min='2'等要求
方法2:保持不可变性(适合React等场景)
如果需要严格遵循状态不可变原则(避免修改原有嵌套对象的引用),可以修改辅助函数,每层都返回新对象:
function setNestedPropImmutable(target, path, value) { if (path.length === 0) return value.toString(); const [firstKey, ...restPath] = path; return { ...target, [firstKey]: setNestedPropImmutable(target[firstKey] || {}, restPath, value) }; } // 使用方式 let stateCopy = {...this.state}; const dictionary = {left:{name:'WORK', min:2, sec:0}, start:true}; function updateImmutableState(obj, parentPath = []) { for (const [key, value] of Object.entries(obj)) { const currentPath = [...parentPath, key]; if (typeof value === 'object' && value !== null && !Array.isArray(value)) { updateImmutableState(value, currentPath); } else { stateCopy = setNestedPropImmutable(stateCopy, currentPath, value); } } } updateImmutableState(dictionary);
内容的提问来源于stack exchange,提问作者DCR
相关产品推荐
相关产品推荐

