如何通过键列表更新JavaScript深层JSON对象的值?
深层对象按键路径更新值的实现方法
先纠正你代码里的两个小细节:
- 对象属性赋值要用冒号,示例里的
x = 4应该改成x: 4 - 键列表
keys里的元素得是字符串,不然会被当作未定义变量,正确写法是const keys = ['section', 'data', 'x'];
下面给两种常用的实现方式:
1. 直接修改原对象(简单高效)
这种方法会直接修改原对象的对应值,适合不需要保留原对象的场景:
// 你的深层对象示例 const myObj = { section: { data: { x: 4 } } }; const keys = ['section', 'data', 'x']; const update = (newValue, keys, obj) => { let current = obj; // 遍历到倒数第二个键,定位到目标值的父对象 for (let i = 0; i < keys.length - 1; i++) { const key = keys[i]; // 可选:如果路径不存在,自动创建空对象避免报错 if (!current[key]) { current[key] = {}; } current = current[key]; } // 给最后一个键赋值 current[keys[keys.length - 1]] = newValue; }; // 调用测试 update(10, keys, myObj); console.log(myObj.section.data.x); // 输出 10
2. 不修改原对象(Immutable 方式)
如果需要保持原对象不变(比如React状态更新场景),可以用递归+对象展开的方式生成新对象:
const updateImmutable = (newValue, keys, obj) => { // 只剩最后一个键时,返回新对象替换对应值 if (keys.length === 1) { return { ...obj, [keys[0]]: newValue }; } // 拆分第一个键和剩余键 const [firstKey, ...restKeys] = keys; // 递归处理剩余路径,生成新的嵌套对象 return { ...obj, [firstKey]: updateImmutable(newValue, restKeys, obj[firstKey] || {}) }; }; // 调用测试 const newObj = updateImmutable(20, keys, myObj); console.log(newObj.section.data.x); // 输出 20 console.log(myObj.section.data.x); // 输出 10,原对象未被修改
内容的提问来源于stack exchange,提问作者Amin Noura
相关产品推荐
相关产品推荐

