Skip to content

getProperty

安全地获取嵌套属性值。

用法

js
import { getProperty } from 'js-cool'

签名

typescript
function getProperty(obj: any, path: string, defaultValue?: any): any

参数

参数类型描述
objany源对象
pathstring属性路径(如 'a.b.c')
defaultValueany未找到时的默认值

返回值

any - 属性值或默认值。

示例

js
const obj = { a: { b: { c: 1 } } }

getProperty(obj, 'a.b.c') // 1
getProperty(obj, 'a.b.d', 'default') // 'default'
getProperty(obj, 'x.y.z') // undefined

相关

基于 MIT 许可发布