Unist Utility to Modify Children

4.0.0 · maintenance · verified Sun Apr 19

unist-util-modify-children is a utility within the unist (Universal Syntax Tree) ecosystem designed to create a reusable function for directly modifying the children of a parent node in an AST. The current stable version is 4.0.0, which notably moved to ESM-only and requires Node.js 16+. Releases generally follow semantic versioning, with major versions introducing breaking changes like environment requirements or module system shifts. A key differentiator and strong recommendation from its maintainers is that most users should probably use `unist-util-visit` instead, as `unist-util-modify-children` is intended for very specific, advanced scenarios where direct, in-place manipulation of child arrays is explicitly required and other traversal utilities are insufficient.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `unist-util-modify-children` with a custom modifier function and apply it to a Unist tree to replace a specific type of parent node with a new structure.

import u from 'unist-builder';
import { modifyChildren } from 'unist-util-modify-children';

// Create a sample Unist tree
const tree = u('root', [
  u('leaf', '1'),
  u('parent', [u('leaf', '2')]),
  u('leaf', '3')
]);

// Define a modifier function that replaces a 'parent' node with a 'subtree' node
const modify = modifyChildren(function (node, index, parent) {
  if (node.type === 'parent') {
    // Replace the 'parent' node with a new 'subtree' node containing its children
    parent.children.splice(index, 1, { type: 'subtree', children: node.children });
    // Return the new index to continue iteration from after the splice
    return index + 1;
  }
});

// Apply the modification to the tree
modify(tree);

// Output the modified tree structure
console.dir(tree, { depth: undefined });

/*
Yields:
{
  type: 'root',
  children: [
    { type: 'leaf', value: '1' },
    { type: 'subtree', children: [{ type: 'leaf', value: '2' }] },
    { type: 'leaf', value: '3' }
  ]
}
*/

view raw JSON →