JavaScript Snippet

Get a Nested Value by Path

Difficulty: Medium

Optional chaining handles statically-known paths, but dynamic dotted strings like `'user.address.city'` or `'items[0].id'` still need a resolver. This snippet walks from the simple dot-only `get`, to a path parser that understands bracket notation and array indices, to a sibling `set` that creates intermediate containers safely. Use them whenever a path comes from config, JSONPath-lite, or a CMS field.

Code Snippets
/

Get a Nested Value by Path

Get a Nested Value by Path

Optional chaining handles statically-known paths, but dynamic dotted strings like `'user.address.city'` or `'items[0].id'` still need a resolver. This snippet walks from the simple dot-only `get`, to a path parser that understands bracket notation and array indices, to a sibling `set` that creates intermediate containers safely. Use them whenever a path comes from config, JSONPath-lite, or a CMS field.

JavaScript
Medium
3 snippets
utility
code-template
js-optional-chaining

681 views

5

When every path is dot-separated and indexes are not allowed, splitting on '.' and walking step by step is the cleanest implementation. The cursor == null || typeof cursor !== 'object' guard short-circuits as soon as the path leaves the object world, which is what callers expect when a key is missing. Returning the explicit fallback instead of undefined lets the caller distinguish "missing" from "set to undefined". Reach for this version when paths come from a config you control.