Quick Take

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
  const 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
  return current;

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



Walk through every single element of an array or key of an object or every string in the given input, use familiar callback function interface (just like Array.forEach or Array.map).


traverse() is an inner method meant to be used by other functions. It does the actual traversal of the AST tree (or whatever input you gave, from simplest string to most complex spaghetti of nested arrays and plain objects). This ~method~ function is used via a callback function, similarly to Array.forEach().

const traverse = require("ast-monkey-traverse");
var ast = [{ a: "a", b: "b" }];
ast = traverse(ast, function (key, val, innerObj, stop) {
let current = val !== undefined ? val : key;
// if you are traversing and "stumbled" upon an object, it will have both "key" and "val"
// if you are traversing and "stumbled" upon an array, it will have only "key"
// you can detect either using the principle above.
// you can also now change "current" - what you return will be overwritten.
// return `NaN` to give instruction to delete currently traversed piece of AST.
return current; // #1 <--- it's obligatory to return it, unless you want to assign it to "undefined"

It's very important to return the value of the callback function (point marked #1 above) because otherwise whatever you return will be written over the current AST piece being iterated.

If you want to delete, return NaN.

innerObj in the callback

When you call traverse() like this:

input = traverse(input, function (key, val, innerObj, stop) {

you get four variables:

  • key
  • val
  • innerObj
  • stop - set stop.now = true; to stop the traversal

If traverse() is currently traversing a plain object, going each key/value pair, key will be the object's current key and val will be the value. If traverse() is currently traversing an array, going through all elements, a key will be the current element and val will be null.

innerObj object's key Type Description
depth Integer number Zero is root, topmost level. Every level deeper increments depth by 1.
path String The path to the current value. The path uses exactly the same notation as the popular object-path opens in a new tab package. For example, a.1.b would be: input object's key a > value is array, take 1st index (second element in a row, since indexes start from zero) > value is object, take it's key b.
topmostKey String When you are very deep, this is the topmost parent's key.
parent Type of the parent of current element being traversed A whole parent (array or a plain object) which contains the current element. Its purpose is to allow you to query the siblings of the current element.
parentType String Either array if parent is array or object if parent is a plain object (not the "object" type, which includes functions, arrays etc.).


Here's how to stop the traversal. Let's gather all the traversed paths first. By the way, paths are marked in object-path opens in a new tab notation (arrays use dots too, a.1.b instead of a[1].b).

const traverse = require("ast-monkey-traverse");
const input = { a: "1", b: { c: "2" } };
const gathered = [];
traverse(input, (key1, val1, innerObj) => {
const current = val1 !== undefined ? val1 : key1;
return current;
// => ["a", "b", "b.c"]

All paths were gathered: ["a", "b", "b.c"].

Now let's make the monkey to stop at the path "b":

const traverse = require("ast-monkey-traverse");
const input = { a: "1", b: { c: "2" } };
const gathered = [];
traverse(input, (key1, val1, innerObj, stop) => {
const current = val1 !== undefined ? val1 : key1;
if (innerObj.path === "b") {
stop.now = true; // <---------------- !!!!!!!!!!
return current;
// => ["a", "b"]

Notice how there were no more gathered paths after "b", only ["a", "b"].

Compared to ast-monkey-traverse-with-lookahead

ast-monkey-traverse can amend AST (it matters what you return within a callback) ast-monkey-traverse-with-lookahead is read-only, it can't amend AST it reads

ast-monkey-traverse does not "see" future nodes, it just reports what it has just traversed ast-monkey-traverse-with-lookahead can report as many nodes "from the future", upon request

Personally, in the context of linting, parsing and other tooling, we're going to use ast-monkey-traverse-with-lookahead because we don't need to mutate the AST, yet we need to "see" what's next in order to patch AST tree errors.


See it in the monorepo opens in a new tab, on GitHub.


To report bugs or request features or assistance, raise an issue on GitHub opens in a new tab.

Any code contributions welcome! All Pull Requests will be dealt promptly.


MIT opens in a new tab

Copyright © 2010–2021 Roy Revelt and other contributors

Related packages:

📦 object-path opens in a new tab
Access deep object properties using a path
📦 ast-monkey 8.0.1
Traverse and edit AST
📦 ast-monkey-util 2.0.1
Utility library of AST helper functions
📦 json-comb-core 7.0.1
The inner core of json-comb
📦 json-variables 11.0.1
Resolves custom-marked, cross-referenced paths in parsed JSON
📦 object-merge-advanced 13.0.1
Recursively, deeply merge of anything (objects, arrays, strings or nested thereof), which weighs contents by type hierarchy to ensure the maximum content is retained
📦 object-boolean-combinations 5.0.1
Consumes a defaults object with booleans, generates all possible variations of it