Skip to content

@pmun/utils / get

Function: get() ​

ts
function get<T>(
   obj, 
   path, 
   defaultValue?): undefined | T;

从对象中获取指定路径的值,支持点分隔的嵌套路径

Type Parameters ​

T ​

T = any

Parameters ​

obj ​

Record<string, any>

源对象

path ​

string

属性路径,如 'user.address.street'

defaultValue? ​

T

路径不存在或值为 undefined 时的返回值,默认为 undefined

Returns ​

undefined | T

路径对应的值,如果路径不存在则返回默认值

Example ​

ts
const obj = { user: { profile: { name: 'Tom', age: 25 }, roles: ['admin'] } }

get(obj, 'user.profile.name') // 'Tom'
get(obj, 'user.roles.0') // 'admin'
get(obj, 'user.settings', { theme: 'dark' }) // { theme: 'dark' }(路径不存在,返回默认值)
get(obj, 'user.profile.gender') // undefined(路径不存在且没提供默认值)
get(obj, 'user.profile.gender', 'unknown') // 'unknown'(使用默认值)