Skip to content

getByPath

输入一个对象obj,和字段所在的路径path,按照路径深度遍历取值。当遍历路径中断或值为undefinednull时,使用defaultValue作为默认值。

Added in v0.0.1

Usage

ts
import { getByPath } from 'parsnip-kit'

getByPath({ a: 1 }, 'a') // 1
getByPath([1], '[0]') // 1
getByPath({ b: [0, 1, 2] }, 'b[2]') // 2
getByPath({ a: [{ b: { c: 'test' } }] }, 'a[0].b.c') // 'test'
getByPath({ a: 1 }, 'a[0].b.c') // undefined
getByPath({ a: 1 }, 'a[0].b.c', 'test') // 'test'

API

Arguments

ArgTypeOptionalDefaultDescription
objobjectfalseundefined待取值的对象
pathstringfalseundefined字段所在的路径
defaultValueanytrueundefined默认值

Returns

Type
any