手写lodash的get函数

以下是手写的 get 函数实现,用于安全地访问嵌套对象属性:

ini 复制代码
javascript
function get(obj, path, defaultValue) {
  // 将路径转换为数组形式
  const pathArray = Array.isArray(path)
    ? path
    : path.split(/.|$$|$$/).filter(p => p !== '');

  let current = obj;

  for (const key of pathArray) {
    if (current === null || current === undefined) {
      return defaultValue; // 遇到null/undefined立即返回默认值
    }
    current = current[key]; // 逐层访问属性
  }

  return current === undefined ? defaultValue : current;
}

实现说明:​

  1. 路径处理

    • path 是数组,直接使用。
    • path 是字符串,按 .[] 分割,并过滤空字符串。例如 'a[0].b' 会被转换为 ['a', '0', 'b']
  2. 逐层访问属性

    • 遍历路径数组,依次访问对象的属性。
    • 若中间遇到 nullundefined,直接返回默认值。
  3. 返回值处理

    • 最终值为 undefined 时返回 defaultValue,否则返回实际值。

示例用法:​

csharp 复制代码
javascript
const obj = { a: { b: [ { c: 3 } ] } };

console.log(get(obj, 'a.b.0.c')); // 3
console.log(get(obj, ['a', 'b', '0', 'c'])); // 3
console.log(get(obj, 'a.x', 'default')); // 'default'
console.log(get(null, 'a.b')); // undefined

注意事项:​

  • 属性名含 .[] 时,需使用数组形式路径(如 ['a.b', 'c'])。
  • 若需支持更复杂的路径(如带引号的字符串),需扩展路径解析逻辑。
相关推荐
奔跑的web.6 小时前
TypeScript Enum 类型入门:从基础到实战
前端·javascript·typescript
盐真卿7 小时前
python2
java·前端·javascript
梦梦代码精7 小时前
BuildingAI vs Dify vs 扣子:三大开源智能体平台架构风格对比
开发语言·前端·数据库·后端·架构·开源·推荐算法
seabirdssss8 小时前
《bootstrap is not defined 导致“获取配置详情失败”?一次前端踩坑实录》
前端·bootstrap·html
kgduu8 小时前
js之表单
开发语言·前端·javascript
谢尔登10 小时前
Vue3 响应式系统——computed 和 watch
前端·架构
愚公移码10 小时前
蓝凌EKP产品:主文档权限机制浅析
java·前端·数据库·蓝凌
欣然~11 小时前
法律案例 PDF 批量转 TXT 工具代码
linux·前端·python
一个小废渣11 小时前
Flutter Web端网络请求跨域错误解决方法
前端·flutter
符文师12 小时前
css3 新特性
前端·css3