Unist Utility to Map Nodes

4.0.0 · active · verified Sun Apr 19

unist-util-map is a utility for the Unist syntax tree ecosystem designed to create a *new* Unist tree by applying a mapping function to every node. Unlike many tree manipulation utilities that mutate the tree in place, `unist-util-map` always returns a completely new, transformed tree, preserving the original structure. The package is currently at version 4.0.0, with a release cadence that includes minor patch updates for bug fixes, documentation improvements, and internal refactors. Major versions are released less frequently, typically when significant breaking changes occur, such as updates to required Node.js versions or shifts to modern module systems. A key differentiator and important consideration for developers is its tree-cloning behavior; while excellent for immutable transformations, this approach can lead to performance overhead on exceptionally large trees. For scenarios involving potentially large trees and relatively few modifications, developers are often advised to consider alternatives like `unist-util-visit` or `unist-util-filter`, which offer different performance characteristics depending on the use case.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to import and use `unist-util-map` to create a new tree where all 'leaf' nodes have their `value` property changed to 'CHANGED', without mutating the original tree.

import {u} from 'unist-builder'
import {map} from 'unist-util-map'

const tree = u('tree', [
  u('leaf', 'leaf 1'),
  u('node', [u('leaf', 'leaf 2')]),
  u('void'),
  u('leaf', 'leaf 3')
])

const next = map(tree, function (node) {
  return node.type === 'leaf'
    ? Object.assign({}, node, {value: 'CHANGED'}) // Return a new object for immutability
    : node
})

// The original tree remains unchanged
console.log('Original tree:', JSON.stringify(tree, null, 2));
// The new tree has 'leaf' nodes with 'CHANGED' value
console.log('Mapped tree:', JSON.stringify(next, null, 2));

// Example using unist-builder for comparison (not a direct dependency)
// npm install unist-builder

view raw JSON →