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

JS根据路径数组提取对象值 终点为对象时取default属性的实现方法

实现思路
  • 用Array.reduce()逐层遍历路径数组,依次访问对象的嵌套属性
  • 遍历结束后判断最终获取到的值的类型:如果是不为null的对象类型,返回其default属性;否则直接返回该值
完整代码
function getValueByPath(sourceObj, pathArr) {
  // 逐层遍历路径获取最终节点的值
  const result = pathArr.reduce((prev, currentKey) => {
    // 可选链避免中间属性不存在时报错
    return prev?.[currentKey];
  }, sourceObj);
  // 注意排除null,因为typeof null 返回 'object'
  return typeof result === 'object' && result !== null ? result.default : result;
}
测试用例

拿你提供的示例对象测试:

const testObj = {
  instituts: {
    default: 999,
    users: { default: 888, email: 777 },
    docs: undefined,
    exams: { price: 3 },
    empowermentTests: 2,
    sessionsHist: 3
  },
  exams: { default: 0 },
  countries: 1,
  levels: 1,
  roles: { default: 1 },
  sessions: 1,
  tests: 1,
  users: { default: 3 },
  options: undefined,
  skills: { default: undefined }
};

console.log(getValueByPath(testObj, ["instituts", "users"])); // 输出 888
console.log(getValueByPath(testObj, ["instituts", "users", "email"])); // 输出777
console.log(getValueByPath(testObj, ["instituts", "empowermentTests"])); // 输出2
console.log(getValueByPath(testObj, ["exams"])); // 输出0
console.log(getValueByPath(testObj, ["skills"])); // 输出undefined

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 02:42:01