如何在JavaScript和TypeScript中更新未知层级的嵌套对象?
嵌套对象基于父级路径更新值的解决方案
针对你需要根据父级路径更新嵌套对象中未知位置节点值的需求,可以利用每个节点自带的parents数组记录的路径,逐层定位到目标节点并更新其value。
核心实现函数
function updateNestedValue(rootObj, parents, targetKey, newValue) { let current = rootObj; // 遍历父级路径,逐层定位到最终父节点 for (let i = 0; i < parents.length; i++) { const parentKey = parents[i]; if (i === 0) { // 根父级直接从根对象中获取 current = current[parentKey]; } else { // 非根父级需要从当前节点的children数组中查找对应对象 const parentItem = current.childern.find(item => item[parentKey]); current = parentItem ? parentItem[parentKey] : null; } if (!current) { throw new Error(`父级路径节点 ${parentKey} 不存在`); } } // 在最终父节点的children中定位目标节点并更新value const targetItem = current.childern.find(item => item[targetKey]); if (targetItem) { targetItem[targetKey].value = newValue; } else { throw new Error(`目标节点 ${targetKey} 在父节点的子项中不存在`); } }
使用示例
以你提供的对象为例,更新key4的value:
// 初始对象 const obj = { "key1":{ "type":"parent", "name":"parent1", "childern":[ { "key2":{ "type":"any", "value":"", "parents":[ "key1" ] }, "key3":{ "type":"parent", "value":"", "parents":[ "key1" ], "childern":[ { "key4":{ "type":"any", "value":"", "parents":[ "key1", "key3" ] } } ] } } ] } }; // 调用函数更新key4的值 updateNestedValue(obj, ['key1', 'key3'], 'key4', '自定义新值'); // 验证结果 console.log(obj.key1.childern[0].key3.childern[0].key4.value); // 输出:自定义新值
注意事项
- 该实现假设每个父节点的
childern数组中,仅有一个对象包含目标子节点的key;如果存在多个匹配项,需要修改find逻辑,比如结合节点其他唯一标识筛选。 - 如果你的对象结构中
childern不是数组而是普通对象,需要调整遍历逻辑,直接通过key访问而非数组查找。 - 函数中加入了基础的错误处理,避免因路径不存在导致程序崩溃,你可以根据需求自定义错误处理逻辑。
内容的提问来源于stack exchange,提问作者Raana Tashakori
相关产品推荐
相关产品推荐

