Frontend Development 13 min read

Deep Data Access in JavaScript: Building the anypath Library for Reading and Writing Nested Structures

This article explains the challenges of reading and writing deeply nested data in JavaScript, introduces native optional‑chaining and TypeScript solutions, and walks through the design and implementation of a reusable anypath library that supports objects, arrays, Maps and Sets.

Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Deep Data Access in JavaScript: Building the anypath Library for Reading and Writing Nested Structures

In this tutorial we explore a common JavaScript problem—accessing and mutating deeply nested data structures—and present a step‑by‑step solution by creating a small library called anypath .

Background

Reading a nested property such as tree.left.a with plain dot notation works only when every intermediate object exists; otherwise a runtime TypeError occurs. Traditional guard code using logical OR or explicit checks quickly becomes verbose for deep paths.

Modern JavaScript (ES2020) provides the optional‑chaining operator ( ?. ) which safely returns undefined when a parent is missing, and TypeScript can catch missing properties at compile time when --strictNullChecks is enabled.

Writing Deep Data

Unlike reading, writing a nested value cannot use optional chaining because the left‑hand side of an assignment must be a definite reference. A naïve guard‑and‑assign approach fails when the intermediate path does not exist, so we need a helper that creates missing containers automatically.

export function setany(obj, key, val) {}

The first implementation parses the dot‑separated key , walks the object, and creates empty objects for missing levels. This works for plain objects but incorrectly treats array indices as object keys.

const tree = {};
setany(tree, 'arr.1', 1); // expected { arr: [1] } but gets { arr: { '1': 1 } }

To distinguish arrays we adopt a [] suffix in the key (e.g., 'arr[].1' ) and adjust the creator to instantiate [] when the suffix is present.

function parseKey(key) { return key.replace('[]', ''); }
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;
}

This version correctly creates objects or arrays based on the key syntax and forms the core of the anypath library.

Extending to Maps and Sets

ECMAScript 2015 introduced Map and Set , which overcome several limitations of plain objects and arrays. The article briefly compares their behavior, key types, and typical usage patterns.

const map = new Map([['a', 1]]);
const obj = { a: 1 };
map.get('a'); // 1
obj.a; // 1

To support these structures in anypath , we can extend the key syntax with a colon and type indicator (e.g., 'arr:Array.0.m:Map.a' ), allowing the library to instantiate the appropriate container automatically.

Reading Deep Data

Reading follows the same path‑splitting logic but does not create missing containers. A simple implementation uses Array.prototype.reduce and the same parseKey helper.

export function getany(obj, key) {
  return key.split('.').reduce((prev, subkey) =>
    prev == null ? prev : prev[parseKey(subkey)], obj);
}

Scaffolding the Project

The library is bootstrapped with the jslib-base CLI, which sets up a TypeScript‑ready project structure (src, test, dist, etc.).

$ npx @js-lib/cli new anypath
# Interactive queries, input project info
$ cd anypath
$ npm i

Conclusion

By combining native optional chaining for reads and the custom setany / getany helpers for writes, the anypath library provides a robust solution for deep data manipulation in JavaScript, with extensibility for advanced containers like Map and Set . The source code is available at https://github.com/jsmini/anypath .

TypeScriptJavaScriptoptional-chaininganypathdeep data accesslibrary development
Rare Earth Juejin Tech Community
Written by

Rare Earth Juejin Tech Community

Juejin, a tech community that helps developers grow.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.