如何实现通过属性名数组获取对象属性的TypeScript函数?
如何实现按路径获取对象属性的TypeScript函数?
需求明确
要写一个TypeScript函数getObjectProperty,接收两个参数:
arr: 字符串数组,代表对象属性的层级路径(比如["info", "home"]表示要取object.info.home)object: 目标对象
函数需要返回路径对应的属性值,只要路径中某一层不存在,就返回undefined。
先修正原函数定义的语法错误(缺少箭头函数的=>),基础结构应该是:
const getObjectProperty = (arr: string[], object: any): any => { // 实现逻辑写在这里 }
测试用的示例对象:
const object = { id: 1, info: { name: "my name", age: 21, home: { city: "New York", address: "Street Name" } }, }
注:原问题里的一个预期结果存在笔误,getObjectProperty(["info", "name", "city"], object) 应该是getObjectProperty(["info", "home", "city"], object),因为name是字符串,没有city属性,修正后才能返回"New York"
两种实用实现方式
方式1:循环遍历路径
最直观的写法,一步步遍历路径中的每个属性,每一步都检查当前值是否有效,避免访问不存在的属性报错:
const getObjectProperty = (arr: string[], object: any): any => { let currentValue = object; for (const key of arr) { // 如果当前值是null/undefined,或者不是对象类型,直接返回undefined if (currentValue == null || typeof currentValue !== 'object') { return undefined; } currentValue = currentValue[key]; } return currentValue; }
方式2:用Array.reduce简化代码
利用数组的reduce方法,把路径数组逐步映射到对象的属性上,代码更简洁,逻辑和循环一致:
const getObjectProperty = (arr: string[], object: any): any => { return arr.reduce((current, key) => { // 只要当前值无效,直接返回undefined,后续迭代不会执行 return current == null || typeof current !== 'object' ? undefined : current[key]; }, object); }
测试验证
把上面的代码代入示例测试,结果完全符合预期:
getObjectProperty(["info", "name"], object)→"my name"getObjectProperty(["info", "home", "city"], object)→"New York"getObjectProperty(["id"], object)→1getObjectProperty(["info", "salary"], object)→undefined
另外,如果传入空数组[],两种实现都会直接返回原对象object,这是合理的默认行为。
内容的提问来源于stack exchange,提问作者Surya Bumantara
相关产品推荐
相关产品推荐

