AST Monkey Traverse

4.1.3 · active · verified Sun Apr 19

ast-monkey-traverse is a utility library designed for traversing Abstract Syntax Trees (ASTs) and general JavaScript object/array structures recursively. The current stable version is 4.1.3. As part of the Codsen monorepo, it receives regular updates and maintenance. Its core functionality offers a simple API, `traverse`, which allows users to visit each node in a data structure, providing access to the current key, value, and an internal object containing contextual information like the current path in object-path notation. A key differentiator is its clear distinction in the callback for object keys/values versus array indices, and its explicit focus on pure ESM since version 3.0.0, which streamlined its module architecture. It also provides built-in TypeScript types, enhancing developer experience for type-safe applications.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to use the `traverse` function to navigate a nested object, identify specific keys, and record their paths.

import { strict as assert } from "assert";
import { traverse } from "ast-monkey-traverse";

const paths = [];
const source = {
  a: {
    foo: {
      bar: [
        {
          foo: "c"
        }
      ],
      d: {
        e: {
          foo: "f"
        }
      }
    }
  }
};

traverse(source, (key, val, innerObj) => {
  // if currently an object is traversed, you get both "key" and "val"
  // if it's array, only "key" is present, "val" is undefined
  let current = val !== undefined ? val : key;
  if (
    // it's object (not array)
    val !== undefined &&
    // and has the key we need
    key === "foo"
  ) {
    // push the path to array in the outer scope
    paths.push(innerObj.path);
  }
  return current;
});

// notice object-path notation "a.foo.bar.0.foo" - array segments use dots too:
assert.deepEqual(paths, ["a.foo", "a.foo.bar.0.foo", "a.foo.d.e.foo"]);

view raw JSON →