Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

traverse

ljharb29mMIT0.6.11TypeScript support: definitely-typed

traverse and transform objects by visiting every node on a recursive walk

traverse, walk, recursive, map, forEach, deep, clone

readme

traverse Version Badge

github actions coverage License Downloads

npm badge

Traverse and transform objects by visiting every node on a recursive walk.

examples

transform negative numbers in-place

negative.js

var traverse = require('traverse');
var obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ];

traverse(obj).forEach(function (x) {
    if (x < 0) this.update(x + 128);
});

console.dir(obj);

Output:

[ 5, 6, 125, [ 7, 8, 126, 1 ], { f: 10, g: 115 } ]

collect leaf nodes

leaves.js

var traverse = require('traverse');

var obj = {
    a : [1,2,3],
    b : 4,
    c : [5,6],
    d : { e : [7,8], f : 9 },
};

var leaves = traverse(obj).reduce(function (acc, x) {
    if (this.isLeaf) acc.push(x);
    return acc;
}, []);

console.dir(leaves);

Output:

[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

scrub circular references

scrub.js:

var traverse = require('traverse');

var obj = { a : 1, b : 2, c : [ 3, 4 ] };
obj.c.push(obj);

var scrubbed = traverse(obj).map(function (x) {
    if (this.circular) this.remove()
});
console.dir(scrubbed);

output:

{ a: 1, b: 2, c: [ 3, 4 ] }

methods

Each method that takes an fn uses the context documented below in the context section.

.map(fn)

Execute fn for each node in the object and return a new object with the results of the walk. To update nodes in the result use this.update(value).

.forEach(fn)

Execute fn for each node in the object but unlike .map(), when this.update() is called it updates the object in-place.

.reduce(fn, acc)

For each node in the object, perform a left-fold with the return value of fn(acc, node).

If acc isn't specified, acc is set to the root object for the first step and the root element is skipped.

.paths()

Return an Array of every possible non-cyclic path in the object. Paths are Arrays of string keys.

.nodes()

Return an Array of every node in the object.

.clone()

Create a deep clone of the object.

.get(path)

Get the element at the array path.

.set(path, value)

Set the element at the array path to value.

.has(path)

Return whether the element at the array path exists.

context

Each method that takes a callback has a context (its this object) with these attributes:

this.node

The present node on the recursive walk

this.path

An array of string keys from the root to the present node

this.parent

The context of the node's parent. This is undefined for the root node.

this.key

The name of the key of the present node in its parent. This is undefined for the root node.

this.isRoot, this.notRoot

Whether the present node is the root node

this.isLeaf, this.notLeaf

Whether or not the present node is a leaf node (has no children)

this.level

Depth of the node within the traversal

this.circular

If the node equals one of its parents, the circular attribute is set to the context of that parent and the traversal progresses no deeper.

this.update(value, stopHere=false)

Set a new value for the present node.

All the elements in value will be recursively traversed unless stopHere is true.

this.remove(stopHere=false)

Remove the current element from the output. If the node is in an Array it will be spliced off. Otherwise it will be deleted from its parent.

this.delete(stopHere=false)

Delete the current element from its parent in the output. Calls delete even on Arrays.

this.before(fn)

Call this function before any of the children are traversed.

You can assign into this.keys here to traverse in a custom order.

this.after(fn)

Call this function after any of the children are traversed.

this.pre(fn)

Call this function before each of the children are traversed.

this.post(fn)

Call this function after each of the children are traversed.

install

Using npm do:

$ npm install traverse

license

MIT

changelog

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog and this project adheres to Semantic Versioning.

v0.6.11 - 2025-01-15

Fixed

  • [Fix] .has should not return true on a falsy node #20

Commits

  • [Deps] update gopd, typedarray.prototype.slice, which-typed-array cc24fd2
  • [Dev Deps] update es-value-fixtures, tape d26f1b4

v0.6.10 - 2024-09-12

Fixed

  • [Fix] continue iterating properly when items are removed #18

Commits

  • [Robustness] minimize use of prototype methods 14f3ef3
  • [Dev Deps] update @ljharb/eslint-config, auto-changelog, tape c232f79
  • [Refactor] protect against an impossible bug 368e82c
  • [Tests] replace aud with npm audit 343a68f
  • [Robustness] use a null object in modifiers 8edc266
  • [Dev Deps] add missing peer dep ecfc692

v0.6.9 - 2024-04-08

Commits

  • [New] support cloning Typed Arrays 18c32c5
  • [New] [Fix] add includeSymbols option; partial revert of "[New] support enumerable Symbol properties" aab373f
  • [Fix] Add "isWritable" before writing to properties 595d64e
  • [actions] remove redundant finisher 7539473
  • [Refactor] use an internal null options object instead of an immutable boolean 0f1e6f1
  • [Deps] update typedarray.prototype.slice, which-typed-array 165f954
  • [Deps] update typedarray.prototype.slice ed483ed
  • [Dev Deps] update tape 5ee670c

v0.6.8 - 2023-12-20

Commits

  • [New] support enumerable Symbol properties 7d659e7
  • [actions] use reusable rebase action 8a04a68
  • [meta] update license text so GitHub can identify it f94bda4
  • [eslint] fix indentation 7c907d6
  • [Dev Deps] update @ljharb/eslint-config, aud, npmignore, tape 8ca47dc
  • [Tests] Stop equal Dates from being flaky b5a9d3a
  • [meta] add missing engines.node 22952cf
  • [actions] update checkout action 17d9faa
  • [actions] update checkout action 5462b41

v0.6.7 - 2022-10-12

Commits

  • [eslint] fix indentation and whitespace 89fc65c
  • [eslint] cleanup 1921966
  • [meta] add auto-changelog c291ed2
  • [actions] add reusable workflows 9a8fd34
  • [Dev Deps] update tape afd6a95
  • [eslint] add eslint 559372e
  • [readme] rename, add badges 0e613fd
  • [meta] create FUNDING.yml; add funding in package.json 26a9ae3
  • [meta] use npmignore to autogenerate an npmignore file 0e09fe6
  • Only apps should have lockfiles e1ac253
  • [meta] update URLs 035e2c0
  • [meta] add safe-publish-latest c2797ac
  • [Tests] add aud in posttest ff93f53

v0.6.6 - 2013-09-23

Commits

  • remove tap as a dep to get around the cyclic library issues 85e1b23
  • guard for the presence of getTime 98f278a
  • use getTime() for firefox browser support ee928ca

v0.6.5 - 2013-08-30

Commits

  • merge the null fix c405df2
  • fix for Cannot convert null to object at hasOwnProperty (native) when node is null d9f52fa

v0.6.4 - 2012-12-17

Commits

v0.6.3 - 2012-06-18

Commits

  • 0.6.3, fixes bugs when the replacement for an object is not an object 09f560c
  • fixed merge conflicts 576832a
  • Update state with the current node before recursing 3857dca
  • Add test for replacing objects with strings and vice-versa 28d5fb6
  • s/Object_keys/objectKeys/g ef3694f
  • Only set state.keys when necessary ee66cd1
  • Fix crash when node is a string and this.update is called with an object. 5c6f161

v0.6.2 - 2012-06-16

Commits

v0.6.1 - 2012-04-06

Commits

  • check builtins using the toString.call trick 459378b
  • support for traversing an Error object. 642dd51
  • fixed the tests for how typeof a regex is now "object" 9250084
  • less annoying constructor 2c5f693
  • bump for error fixes 6b78600

v0.6.0 - 2012-02-20

Commits

  • has() with tests, documented get() and set() too aeebf14

v0.5.2 - 2011-10-16

Commits

  • Should be able to stop traversing when removing or deleting 4aa61ef
  • relative requires for the tests 9d4d4c5
  • Added documentation for stopHere-flag on remove and delete 2bb8018
  • bump for stopHere on delete and remove a23839a

v0.5.1 - 2011-08-23

Commits

  • fix for brokenness in IE with using the wrong variable name for the prototype checking 4cb7bcb

v0.5.0 - 2011-08-23

Commits

  • spun off deepEqual into a utility library 9d5148a
  • traverse now works with all the IEs 96d9e25
  • tests all updated for the removal of deepEqual from the main lib 9ebde92
  • stubs for non-es5 browsers, didn't break any unit tests 559a6f1

v0.4.6 - 2011-07-27

Commits

  • some minor adjustments to expose keys for sibling calculations a936bea

v0.4.5 - 2011-07-24

Commits

  • include circular ref example in the readme, Traverse => traverse 4a6285f
  • scrub example ec1fb18
  • bump for exposing parents 5cb4ecb
  • export 'parents' to context 5af2f8d

v0.4.4 - 2011-07-20

Commits

  • allow setting of keys (ordering) in before modifier 9fb8e2c
  • note about this.keys, bump 1148bc7

v0.4.3 - 2011-06-14

Commits

v0.4.2 - 2011-06-11

Commits

  • bump to 0.4.2 for this.block() with a passing test d945818
  • note about stopHere for update() in the readme 18f3e27

v0.4.1 - 2011-06-10

Commits

  • moved stop behavior in updates into a second keepGoing argument 1d31897

v0.4.0 - 2011-06-10

Commits

  • an amazing number of test descriptions were getting ignored 1d043f0
  • better failing super deep test 01d35ce
  • stop() passes its test 79d615f
  • passing test for deep reduce and this.stop() 9aea0a1
  • subexpr test passes by checking if update() happened 44e731b
  • passing new tests yay 3d5057a
  • failing test for this.stop() 090c3d4
  • subexpressions from update()s shouldn't be traversed, failing test be2b574
  • passing test for stop map too hooray 0ee24cc
  • test for arity shows more bugs da698d6

v0.3.8 - 2011-06-06

Commits

  • tests for some bugs in deepEqual 2b15a41
  • deep equal tests now pass, delete map tests fail though bfdc40e
  • delete map redux test also passes for deleted element construction syntax [,,,] etc 56553ff
  • now passing all the equality tests again 6721461
  • tests for remove() and delete() f5d429a
  • remove tests 7010fe2
  • better failing levels test for deepEqual 73efbe5
  • failing deepEqual comparison with undefined throws 0a6d27d
  • remove unused seq devDependency, bump expresso version 0c1e021

v0.3.7 - 2011-06-05

Commits

  • now with syntax-highlightable markdown snippets d4a7710
  • failing circular map scrub test 9f36635
  • fix for immutable removal, bump to 0.3.7 9528471

v0.3.6 - 2011-06-03

Commits

  • tests for not-yet-written deepEqual() 5267ae1
  • deepEqual now passes several tests 6fe06a5
  • dox for deepEqual 5eab662
  • untested get and set 7fa7247
  • missing comma fixed the regexp test and also an implementation for typeof "function" fc23e4f
  • a passing test for the other case of structural deep circular reference checking 04e5492
  • some tests were wrong, regexp test rightly still fails b9d1110
  • circular test for topological circular equality passes b423996
  • and another test just in case for non-root circular ref checks a914717
  • actually check function equality, all tests now passing cb7c1b0

v0.3.5 - 2011-05-28

Commits

  • took out up-front cloning, only fails date test 718d01b
  • cleaned up root handling, fails circDubMap still 9ed99f3
  • updated tests for expresso updates ages ago f95bf5e
  • passes all its tests again d0dac52

v0.3.4 - 2011-04-16

Commits

  • updated readme for this.delete() and this.remove() e4cea30
  • quote the delete keyword 42d0460

v0.3.3 - 2011-04-15

Commits

  • this.remove() and this.delete() with passing tests d603771

v0.3.2 - 2011-04-10

Commits

  • now traverses over dates correctly and should work for other builtins bb8d1b5
  • failing date map test a504425
  • forgot the console.dir fb2c472

v0.3.1 - 2011-02-18

Commits

  • updated readme and examples for the new interface changes aa2d4f3
  • mutability tests all pass 36df874
  • updated tests to not use sys anymore 7a0969f
  • simpler clone implementation 6a6cb49
  • double circular ref test failing, not aggressive enough d190897
  • reduce() now too c89ae4b
  • fix for isRoot, check path.length, not node === root 423066e
  • passing circular ref update forEach test but failing for likewise with map d411695
  • trade some space savings for less agressive circular reference algorithm (the same as console.dir it seems) ee52d80
  • failing test for circular ref updates 42b6b84

v0.3.0 - 2011-02-18

Commits

  • completely rewrote Traverse, deleted hash.js and web.js 414c726
  • tests pass again with the rewrite f0f76cc

v0.2.4 - 2011-02-03

Commits

  • for some silly reason I was requiring sys 95712d9

v0.2.3 - 2010-11-19

Commits

  • a hash exclude test and a package bump 536b93d
  • exclude to remove keys 752f64f

v0.2.2 - 2010-10-25

Commits

v0.2.1 - 2010-09-11

Commits

  • better compatability fallbacks for ff, maybe ie 33577aa
  • compact and size for Hash (can't do .length since the function prototype has that) b9e6db5
  • more correct string behavior in stringify example b9750ff

v0.2.0 - 2010-09-08

Commits

  • deepEquals to make the tests simpler a962ed8
  • top-level Hash functions more closely mirror Hash() functions 35298be
  • .has with tests 02727cf
  • test for valuesAt and now takes a single non-array key too 3487771
  • take out memoization since it breaks if the hash gets modified outside the fluent interface 67b6d3d
  • zip and zip constructor 616514e
  • zip test passes 0226636

v0.1.4 - 2010-09-08

Commits

  • test for compact passes ec171ba
  • compact like in ruby, but for hashes 0d8e1e6

v0.1.3 - 2010-09-04

Commits

  • add stringify to examples 6683529
  • now isArray and instanceof works for arrays fa2d72b

v0.1.2 - 2010-09-04

Commits

  • pushed walk() out of map e7ec7de
  • modifiers seem to work f0ee567
  • stringify test for new modifiers 6de18e5
  • before, after, and between callbacks to fancier traversing 5662b6f
  • updated readme and negative example with new style 5aa3f84
  • deprecated .get() in favor of .value a8d1645
  • non-coerced root test fixes an odd bug with array traversal f22580a

v0.1.1 - 2010-09-04

Commits

  • only update when this.update is still around, tests for Traverse.functions cc59d56
  • deprecate modify in favor of map f018025
  • fix nodes and paths 78edd30
  • use return values to auto-update bc68fa5

v0.1.0 - 2010-09-03

Commits

  • circular refs don't crash it now 2cdd854
  • new top-level map forEach paths and nodes e508823
  • package bump to 0.1.0 and should work in IE better now too 4400d88

v0.0.9 - 2010-08-27

Commits

  • broke up test into separate exports 92046a4
  • forgot the return in ('traverse/web').source() 188ee17

v0.0.8 - 2010-08-26

Commits

  • memoization for keys, values, length 9cffe15
  • merge, update, and tap df5b737
  • length, clone, and copy 249ec0f
  • updated readme and f.call(self) 03f6f1e
  • more explicit about the licensing (MIT/X11) c452103
  • oh right and this example file d98c125
  • updated readme for hash traversal a56b629
  • tests for update, concat, and merge all pass 7fc4eca
  • updated readme for hash stuff 094ab55
  • more tests, all pass 2d9f7a2
  • key and value getters 459def9
  • stupid markdown parens 0bd932b
  • new valuesAt and extract functions 883f015
  • tests for valuesAt and extract pass 86d71a9
  • hash example, some() c7a133c
  • key and value tests 92212e5
  • copy instead of clone for merge 4fcece2

v0.0.7 - 2010-08-26

Commits

  • new hash lib and clone sugar 586124c
  • hash test for map 393444a
  • a test for instances 1adf75a
  • new modules format for package.json, boost to 0.0.7 0f11600
  • proto trick to make instanceof work on cloned objects 130a833

v0.0.6 - 2010-08-01

Commits

  • magical webified version of traverse with require('dnode/web').source() 0043cd6
  • directories.lib, I forgot. Also scrub requires for later 2a1f530

v0.0.5 - 2010-07-28

Commits

  • test for stupid .constructor() bug 6b9d85d
  • stupid traversal bug, version bump 4cf36f3

v0.0.4 - 2010-07-27

Commits

  • now using expresso for test suite, json test written 7d448da
  • leaves and negative tests to go with the example, also s/tests/test/ 13e19bf
  • clone in the constructor so updates don't mess up the root object's refs fc5903b
  • readme updates for expresso tests and version bump to 0.0.4 6993515

v0.0.3 - 2010-07-21

Commits

  • backwards compatible update for var Traverse = require('traverse') style d0f50e9

v0.0.2 - 2010-07-14

Commits

  • special check for null, for which typeof(null) == 'object' a4128c0
  • installation in readme a6fc0d6
  • add output to negative example 590045e
  • license file 519fd1f
  • s/127/128/ 5fcb3f5

v0.0.1 - 2010-07-08

Commits

  • initial commit with forEach, modify, get, paths, nodes e73bba8
  • more examples 16bf66e
  • readme with json example fa8265b
  • json example 607de69
  • leaf example 23ccea5
  • package.json file for version 0.0.1 c3266e0
  • npm doesn't like newlines in package.json strings 6840d4e