Deep Data Access in JavaScript and Building the anypath Library
This article examines the challenges of reading and writing deeply nested JavaScript data, explains why traditional defensive checks fail, introduces optional chaining and TypeScript strict null checks, and presents the anypath library with setany/getany functions that automatically create missing objects or arrays while supporting future extensions for Map and Set.
In this article we explore the common challenge of accessing and mutating deeply nested data in JavaScript, illustrating why simple property access can cause runtime errors when intermediate objects are undefined.
We review traditional defensive patterns such as logical‑OR short‑circuit checks, their limitations for deep hierarchies, and modern language features like optional chaining (?.) and TypeScript’s strict null checks that provide compile‑time safety.
To address the lack of a native deep‑write solution, we design and implement a small library called anypath . The library exposes setany(obj, key, value) to set a value at an arbitrary dot‑separated path, automatically creating missing objects or arrays (using an [] suffix to denote array containers).
export function setany(obj, key, val) {
const keys = key.split('.');
const root = keys.slice(0, -1).reduce((parent, subkey) => {
const realkey = parseKey(subkey);
return (parent[realkey] = parent[realkey]
? parent[realkey]
: subkey.includes('[]')
? []
: {});
}, obj);
root[keys[keys.length - 1]] = val;
}The initial implementation parses the key, walks the path with reduce , and creates default containers when they do not exist. We then extend the parser to recognise array notation and discuss how the same approach could be expanded to support Map and Set containers by adding a type suffix (e.g., :Map ).
We also provide a complementary getany(obj, key) function that reads a value from a deep path without mutating the structure, using the same key‑parsing logic.
export function getany(obj, key) {
return key.split('.').reduce((prev, subkey) =>
prev == null ? prev : prev[parseKey(subkey)], obj);
}Finally, we briefly compare native JavaScript objects with ES6 Map and Set , highlighting their key‑type flexibility and uniqueness guarantees, and show how these structures could be integrated into the anypath API.
The article concludes with a link to the GitHub repository where the full source code and scaffolding generated by jslib-base can be found.
Rare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.