Deviopath › TypeScript

Get a Value by Path

Hard · Parsing

Write getPath(obj, path, fallback) that reads a nested value using a path string.

Path syntax:

- name or .name reads a property.

- [2] reads an array index.

- ["any key"] reads a property whose name can contain dots (the key has no " inside).

For example items[1].meta["is.ok"] has the segments items, 1, meta, is.ok. An empty path returns obj itself.

Only step into objects and arrays: if the current value is anything else (including null or a string) before a segment, return fallback. If the final value is undefined, return fallback. A final null is returned as null.

Tip: first write parsePath(path): Segment[].

Next: Sort Semantic Versions