欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

前端中级工程师 - 手写编程问题 - 题目 3

最编程 2024-05-05 20:32:37
...

描述: 完成 deepGet 函数,给它传入一个对象和字符串,字符串表示对象深层属性的获取路径,可以深层次获取对象内容

const deepGet = (obj, prop) => {
  
}


deepGet(
  {
    school: {
      student: { name: 'Tomy' }
    }
  },
  'school.student.name'
) 

deepGet(
  {
    school: {
      students: [{ name: 'Tomy' }, { name: 'Lucy' }]
    }
  },
  'school.students[1].name'
) 


deepGet({ user: { name: 'Tomy' } }, 'user.age') 
deepGet({ user: { name: 'Tomy' } }, 'school.user.age') 

分析: 这题考察对数组以及对象方法的使用

实现方案:

const deepGet = (obj, prop) => {
  
  const keyArr = prop.split('.').map(item => item)

  const reducer = (acc, cur) => {
    
    const objKey = cur.includes('[') && cur.replaceAll(/[\[?=0-9\]$]/gi, '')
    if (Array.isArray(acc[objKey])) {
      
      cur = cur.replaceAll(/[^?=0-9]/gi, '')
      return acc[objKey][cur] || {}
    }
    return acc[cur] ? acc[cur] : {}
  }

  const result = keyArr.reduce(reducer, obj)
  return Object.keys(result).length ? result : undefined
}