Path to prop 🛤
npm i path-to-prop
Retrieves a property from an object based on a 'path/to.that.prop'
- Supports paths with both
/
and .
to separate props - Safely typed (with TypeScript) - returns
unknown
Usage
import { getProp } from 'path-to-prop'
getProp({ nested: { prop: 1 } }, 'nested.prop')
getProp({ nested: { prop: 1 } }, 'nested')
You can use /
or .
to access nested props:
const obj = {a: {b: {c: {d: {e: 1}}}}}
const path = 'a/b/c.d.e'
getProp(obj, path)
getProp(obj, 'nonexistent.prop')
When you have /
or .
in your prop names, use an array:
const obj = {'a/b': {'c.d': 1}}
getProp(obj, ['a/b', 'c.d'])