wild-wild-path

repository·main·Indexed 20 days ago

https://github.com/ehmicky/wild-wild-path

A utility for accessing, setting, and removing object properties using a powerful query syntax that supports wildcards, regexps, slices, and unions. Version 5.0.1 provides functions such as get(), set(), has(), list(), remove(), and a memory-efficient iterate() generator for traversing complex object structures.

Tokens
7.2K
Snippets
34
Records
37
Agent score
72%

What's inside wild-wild-path

  1. Install wild-wild-path via npm

    main

    Install the package using npm. This project is an ES module and requires Node.js >=18.18.0 or a modern browser.

    Important Requirements:

    • Use import or import() statements; require() is not supported.
    • If using TypeScript, configure your project to output ES modules rather than CommonJS.
    npm install wild-wild-path
  2. How missing values are handled during path traversal

    main

    When performing path operations like set(), the library may encounter missing values. The library distinguishes between 'known' missing properties (e.g., those identified by prop, index, or slice tokens) and 'unknown' missing properties (e.g., those identified by any or regexp tokens).

    • set(): Automatically creates missing entries deeply by default.
    • list(), get(), has(): Do not create missing entries. Instead, they use a missing property to signal whether a value was found or if a default was used.

    To control this behavior, the getMissingValue function can be used to determine if a value should be replaced with a default based on the provided missing flag and classes configuration.

  3. Iterate over matching properties with iterate()

    main

    Use iterate(target, query, options?) to return an Iterable<any> of all properties matching the query.

    Note: This is more memory-efficient than list() but is slower for small datasets.

    const target = { settings: { colors: ['red', 'blue'] } }
    
    for (const color of iterate(target, 'settings.colors.*')) {
      console.log(color) // 'red', 'blue'
    }
  4. Get a property with get()

    main

    Use get(target, query, options?) to return the first property matching the query.

    • target: The object or array to search.
    • query: A string path, array of path segments, or regex.
    • options: Optional configuration.

    Returns any | undefined.

    const target = { settings: { colors: ['red', 'blue'] } }
    
    get(target, 'settings.colors.0') // 'red'
    get(target, ['settings', 'colors', 0]) // 'red'
  5. List all matching properties with list()

    main

    Use list(target, query, options?) to return all properties matching the query as an array.

    Supported query types include:

    • Unions: Space-separated paths (e.g., 'path.one path.two').
    • Arrays of paths: [['path', 'one'], ['path', 'two']].
    • Regexps: Using regex patterns (e.g., 'user./Name/').
    • Wildcards: * or **.
    • Slices: 0:2.

    If { entries: true } is passed in options, it returns an array of objects containing { value, path, missing } instead of just values.

    const target = {
      userOne: { firstName: 'John', lastName: 'Doe', age: 72 },
      userTwo: { firstName: 'Alice', colors: ['red', 'blue', 'yellow'] },
    }
    
    list(target, 'userOne.firstName userTwo.colors.0') // ['John', 'red']
    list(target, [['userOne', 'firstName'], ['userTwo', 'colors', 0]]) // ['John', 'red']
    list(target, 'userOne./Name/') // ['John', 'Doe']
    list(target, ['userOne', /Name/]) // ['John', 'Doe']
    list(target, 'userTwo.colors.*') // ['red', 'blue', 'yellow']
    list(target, 'userTwo.colors.0:2') // ['red', 'blue']
    list(target, '**.firstName') // ['John', 'Alice']
    
    list(target, 'userOne.*', { entries: true })
    // [
    //   { value: 'John', path: ['userOne', 'firstName'], missing: false },
    //   { value: 'Doe', path: ['userOne', 'lastName'], missing: false },
    //   { value: 72, path: ['userOne', 'age'], missing: false },
    // ]
  6. Remove properties with remove()

    main

    Use remove(target, query, options?) to delete all properties matching the query.

    • Return Value: Returns the Target. By default, it returns a deep clone. To modify the original object, set { mutate: true } in options.
    const target = { user: { firstName: 'John', lastName: 'Doe', age: 72 } }
    
    remove(target, 'user.lastName') // { user: { firstName: 'John', age: 72 } }
    remove(target, 'user./Name/') // { user: { age: 72 } }
    remove(target, ['user', /Name/]) // { user: { age: 72 } }
  7. Set properties with set()

    main

    Use set(target, query, value, options?) to set all properties matching the query to the provided value.

    • Return Value: Returns the Target. By default, it returns a deep clone. To modify the original object, set { mutate: true } in options.
    • Path Creation: If the path does not exist, it will be created (e.g., set({}, 'user.0.color', 'red') creates the nested structure).
    • Missing Option: If { missing: false } is passed, it will not create new paths if they don't exist.
    const target = { colors: ['red', 'blue'] }
    
    set(target, 'colors.0', 'yellow') // ['yellow', 'blue']
    set(target, ['colors', 0], 'yellow') // ['yellow', 'blue']
    set(target, 'colors.-1', 'yellow') // ['red', 'yellow']
    set(target, 'colors.-0', 'yellow') // ['red', 'yellow', 'blue']
    set(target, 'colors.*', 'yellow') // ['yellow', 'yellow']
    set({}, 'user.0.color', 'red') // { user: [{ color: 'red' }] }
    set({}, 'user.0.color', 'red', { missing: false }) // {}
  8. Check for property existence with has()

    main

    Use has(target, query, options?) to return a boolean indicating whether the query matches any property in the target.

    Returns boolean.

    const target = { settings: { lastName: undefined, colors: ['red', 'blue'] } }
    
    has(target, 'settings.firstName') // false
    has(target, ['settings', 'firstName']) // false
    has(target, 'settings.lastName') // true
  9. Configure search behavior with Options

    main

    The Options object allows you to fine-tune how queries match and how results are returned.

    Matching Logic

    • childFirst: (boolean) When using unions/deep wildcards, sorts results from children to parents. Default: false.
    • roots: (boolean) When true, only matches the highest level of a match (ignores children if a parent matches). Default: false.
    • leaves: (boolean) When true, only matches the lowest level of a match (ignores parents if a child matches). Default: false.
    • shallowArrays: (boolean) If true, wildcards do not recurse into arrays. Default: false.
    • classes: (boolean) If true, wildcards/regexps include non-plain objects like class instances or errors. Default: false.
    • inherited: (boolean) If true, includes inherited properties (but not non-enumerable ones). Default: false.

    Result Formatting

    • sort: (boolean) Sorts sibling object properties lexicographically by name. Default: false.
    • entries: (boolean) If true, returns Entry objects ({ value, path, missing }) instead of raw values. Default: false.
    • missing: (boolean) If true, includes properties not defined in the target. Default: false for list|iterate, true for set.

    Mutation

    • mutate: (boolean) If true, set() and remove() mutate the target directly instead of returning a deep clone. Default: false.
    // Example: childFirst
    const target = { user: { name: 'Alice' } }
    list(target, 'user.**', { childFirst: true }) // ['Alice', { name: 'Alice' }]
    
    // Example: roots
    list(target, 'user.**', { roots: true }) // [{ name: 'Alice' }]
    
    // Example: leaves
    list(target, 'user.**', { leaves: true }) // ['Alice']
  10. Use query strings for expressive queries

    main

    Query strings are ideal for CLI usage and serialization. They support several advanced features:

    • Deep properties: Use dots for object properties or array indices (e.g., user.colors.0).
    • Unions: Use space-delimited strings for
  11. Use wild-wild-utils for higher-level operations

    main

    For more advanced functional operations, use the companion library wild-wild-utils. It provides the following methods:

    • map()
    • merge()
    • push()
    • unshift()
    • find()
    • pick()
    • include()
    • exclude()
    • flatten()