You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript如何无需逐层指定键路径更新任意深度嵌套字典的值

JavaScript 任意深度嵌套对象值更新实现

核心通用函数

这个函数支持传入点分隔的路径字符串或者路径数组,无需逐层写键访问即可完成嵌套值更新:

function updateNestedValue(obj, keyPath, value) {
  const keys = Array.isArray(keyPath) ? keyPath : keyPath.split('.');
  let current = obj;
  for (let i = 0; i < keys.length - 1; i++) {
    const key = keys[i];
    if (current[key] === undefined) {
      throw new Error(`路径 ${keys.slice(0, i + 1).join('.')} 不存在`);
    }
    current = current[key];
  }
  current[keys.at(-1)] = value;
  return obj;
}

使用示例

针对你给出的嵌套对象结构:

const dict = {
  "group1" : {
    "name" : "NAME1"
  },
  "group2" : {
    "name" : "NAME2"
  }
}

直接调用函数传入路径即可完成更新:

// 字符串路径写法
updateNestedValue(dict, 'group1.name', 'Bob White');

// 数组路径写法,适合键名本身包含点的场景
// updateNestedValue(dict, ['group1', 'name'], 'Bob White');

console.log(dict.group1.name); // 输出:Bob White

拓展:支持自动创建中间路径

如果需要给不存在的中间路径直接赋值(不需要提前创建层级),可以使用以下修改版本:

function updateNestedValueAutoCreate(obj, keyPath, value) {
  const keys = Array.isArray(keyPath) ? keyPath : keyPath.split('.');
  let current = obj;
  for (let i = 0; i < keys.length - 1; i++) {
    const key = keys[i];
    if (current[key] === undefined) {
      current[key] = {};
    }
    current = current[key];
  }
  current[keys.at(-1)] = value;
  return obj;
}

使用示例:

// 无需提前创建group3、info层级
updateNestedValueAutoCreate(dict, 'group3.info.age', 18);
console.log(dict.group3.info.age); // 输出:18

内容的提问来源于stack exchange,提问作者SunAwtCanvas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 04:36:05