Pathfinder

Overview

Pathfinder is a pivotal class in MonsterJS, designed to navigate and manipulate data within nested object structures. It provides a straightforward way to access or modify deeply nested values using a concise path notation.

Key Features

  • Deep Access: Quickly retrieve or set values at any depth within an object or array.
  • Path Notation: Utilize a dot-separated string or an array of keys/indices to specify paths.
  • Flexibility: Works with objects, arrays, and even complex nested structures.
  • Wildcards: Supports wildcard characters to apply operations across multiple paths.

Methods and Properties

Constructor

Initializes a Pathfinder instance with a target object to operate on.

getVia(path)

Retrieves the value at the specified path within the object. Throws an error if the path is invalid or does not exist.

setVia(path, value)

Sets the value at the specified path. If the path doesn’t exist, it creates the necessary structure.

deleteVia(path)

Removes the value at the specified path, adjusting the structure if necessary.

exists(path)

Checks if a value exists at the specified path without throwing errors.

Examples

Accessing a nested value:

import { Pathfinder } from '@schukai/monster/source/data/pathfinder.mjs';

const data = {
    a: { b: { c: 10 } }
};
const pathfinder = new Pathfinder(data);
console.log(pathfinder.getVia('a.b.c')); // Outputs: 10

Setting a nested value:

pathfinder.setVia('a.b.d', 20);
console.log(data.a.b.d); // Outputs: 20

Checking for the existence of a path:

console.log(pathfinder.exists('a.b.c')); // Outputs: true
console.log(pathfinder.exists('a.x.y')); // Outputs: false

Pathfinder enhances data manipulation in MonsterJS, making it easier to work with complex data structures through its intuitive API and versatile path navigation capabilities.