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

如何通过键列表获取嵌套对象的值并封装为get_value函数?

实现嵌套对象的键列表取值函数

这是个很实用的日常开发需求,我给你分享几种简洁可靠的实现方式,还会覆盖一些边界情况的处理:

方法1:基础循环遍历

这是最直观的实现思路——顺着键列表一步步深入嵌套对象:

function get_value(obj, key_list) {
  let current = obj;
  for (const key of key_list) {
    // 提前判断:如果当前值不存在/不是对象,直接返回undefined避免报错
    if (current == null || typeof current !== 'object') {
      return undefined;
    }
    current = current[key];
  }
  return current;
}

测试示例:

const obj = { a: { b:{ c:"c" } } };
const t = ["a", "b", "c"];
console.log(get_value(obj, t)); // 输出 "c"
console.log(get_value(obj, ["a", "x"])); // 输出 undefined

方法2:使用Array.reduce()

利用数组的reduce方法可以让代码更紧凑,本质逻辑和循环一致,但写法更优雅:

function get_value(obj, key_list) {
  return key_list.reduce((current, key) => {
    // 同样做边界防护
    if (current == null || typeof current !== 'object') {
      return undefined;
    }
    return current[key];
  }, obj); // 初始累加值传入原对象
}

额外补充:处理空键列表的场景

如果你的业务中可能出现空的键列表,可以在函数开头加个兜底判断:

function get_value(obj, key_list) {
  if (key_list.length === 0) {
    return obj; // 键列表为空时直接返回原对象
  }
  return key_list.reduce((current, key) => {
    if (current == null || typeof current !== 'object') {
      return undefined;
    }
    return current[key];
  }, obj);
}

可选:抛出异常替代返回undefined

如果希望在中间键不存在时明确抛出错误方便调试,可以修改判断逻辑:

function get_value(obj, key_list) {
  let current = obj;
  for (const key of key_list) {
    if (current == null || !(key in current)) {
      throw new Error(`键 "${key}" 在当前对象中不存在`);
    }
    current = current[key];
  }
  return current;
}

内容的提问来源于stack exchange,提问作者sof-03

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:22:56