uce/site/doc/pages/each.txt

37 lines
1.4 KiB
Plaintext

:sig
void DTree::each(function<void (const DTree& item, String key)> f) const
:params
f : callback invoked per child with the child node and its key
return value : none
:see
>types
0_DTree
dtree_map
dtree_filter
dtree_keys
is_list
:content
Iterates a `DTree`. This is a read accessor: it is `const`, never creates or modifies nodes, and dereferences internal references automatically.
For map-shaped nodes the callback runs once per child, in key order, receiving the child and its key. For scalar nodes it runs exactly once with the node itself and an empty key.
The callback receives the child as `const DTree&` — no copy is made, and all read accessors (`to_string()`, `to_s64()`, `get_by_path()`, ...) work on it directly:
```cpp
rows.each([&](const DTree& row, String key) {
out("<li>", html_escape(row.get_by_path("title").to_string("Untitled")), "</li>");
});
```
Declaring the callback parameter as plain `DTree` also works but deep-copies every child; prefer `const DTree&`. To transform or filter into a new tree, use `dtree_map()` / `dtree_filter()` instead of mutating inside the callback.
List-shaped trees (see `is_list`) iterate in numeric index order, matching `json_encode()` and the other serializers. Keyed maps iterate in string key order.
## Related Concepts
- PHP: `foreach ($tree as $key => $item)`
- JavaScript: `Object.entries(obj).forEach(([key, item]) => ...)`