§ 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-path opens 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

MIT opens in a new tab

Copyright © 2010–2020 Roy Revelt and other contributors

Related packages:

📦 ast-loose-compare 1.8.16
Compare anything: AST, objects, arrays and strings
📦 ast-monkey 7.11.22
Traverse and edit AST
📦 ast-delete-object 1.9.2
Delete all plain objects in AST if they contain a certain key/value pair
📦 ast-deep-contains 1.1.21
Like t.same assert on array of objects, where element order doesn't matter.
📦 ast-monkey-traverse 1.12.20
Utility library to traverse AST
📦 ast-contains-only-empty-space 1.9.16
Returns Boolean depending if passed AST contain only empty space