ast-get-values-by-key2.7.0

Read or edit parsed HTML (or AST in general)

§ Quick Take

import { strict as assert } from "assert";
import getAllValuesByKey from "ast-get-values-by-key";

// GETTER
// ======

// returns "object-path" notation paths where arrays use dots:
assert.deepEqual(
  getAllValuesByKey(
    {
      parsed: [
        {
          tag: "html",
        },
      ],
    },
    "tag" // value to search for
  ),
  [{ val: "html", path: "parsed.0.tag" }]
);

// SETTER
// ======

assert.deepEqual(
  getAllValuesByKey(
    {
      parsed: [
        {
          tag: "html",
        },
      ],
      foo: {
        tag: null,
      },
      bar: {
        tag: null,
      },
    },
    "tag", // value to search for
    [123, 456] // pot of values to pick from (one result not enough)
  ),
  {
    parsed: [
      {
        tag: 123,
      },
    ],
    foo: {
      tag: 456,
    },
    bar: {
      tag: null, // value pot was depleted and there was nothing left to put here
    },
  }
);

§ Examples

§ Purpose

There are many ways to work with AST's — huge nested trees of objects and arrays. This program is one of possible ways.

Two arguments triggers the GET mode — it returns an array of objects with value-path findings.

If you map that into desired values array and run it again, this time putting desired values as third input argument, you get the SET mode.

§ API

getAllValuesByKey(input, whatToFind, replacement)

  • If two arguments are given, it's getter. You'll receive an array of zero or more plain objects with keys: val and path, where path follows object-pathopens in a new tab notation.

  • If three arguments are given, it's setter. You'll receive a copy of original input, changed accordingly.

This library does not mutate any input arguments.

Input argumentTypeObligatory?Description
inputAnyyesSomething to work upon
whatToFindString or array of stringsyesThe Optional Options Object, see below for its API

§ Licence

MITopens in a new tab

Copyright © 2010–2020 Roy Revelt and other contributors

Related packages:

📦 ast-get-object 1.9.18
Getter/setter for nested parsed HTML AST's, querying objects by key/value pairs
📦 ast-monkey-traverse 1.12.20
Utility library to traverse AST
📦 ast-loose-compare 1.8.16
Compare anything: AST, objects, arrays and strings
📦 ast-is-empty 1.10.10
Find out, is nested array/object/string/AST tree is empty
📦 ast-monkey-util 1.1.11
Utility library of AST helper functions
📦 ast-contains-only-empty-space 1.9.16
Returns Boolean depending if passed AST contain only empty space