object-delete-key examples

Table of Contents

Quick Take

import { strict as assert } from "assert";
import { deleteKey } from "object-delete-key";

// deleting key 'c', with value 'd'
assert.deepEqual(
  deleteKey(
    {
      a: "b",
      c: "d",
    },
    {
      key: "c",
      val: "d",
    }
  ),
  { a: "b" }
);

// deleting key 'b' with value - array ['c', 'd']
assert.deepEqual(
  deleteKey(
    {
      a: { e: [{ b: ["c", "d"] }] },
      b: ["c", "d"],
    },
    {
      key: "b",
      val: ["c", "d"],
    }
  ),
  {}
);
// notice program cleaned after itself, it didn't leave empty "a" key

Deletion by the key only

import { strict as assert } from "assert";
import { deleteKey } from "object-delete-key";

assert.deepEqual(
  deleteKey(
    {
      a: "a",
      b: "jlfghdjkhkdfhgdf",
      c: [{ b: "weuhreorhelhgljdhflghd" }],
    },
    {
      key: "b",
    }
  ),
  { a: "a" }
);

Deletion by the value only

import { strict as assert } from "assert";
import { deleteKey } from "object-delete-key";

assert.deepEqual(
  deleteKey(
    {
      a: "a",
      skldjfslfl: "x",
      c: [{ dlfgjdlkjlfgjhfg: "x" }],
    },
    {
      val: "x",
    }
  ),
  { a: "a" }
);

// same but without cleanup:
assert.deepEqual(
  deleteKey(
    {
      a: "a",
      skldjfslfl: "x",
      c: [{ dlfgjdlkjlfgjhfg: "x" }],
    },
    {
      val: "x",
      cleanup: false,
    }
  ),
  {
    a: "a",
    c: [{}], // <--- !
  }
);

Disable the cleanup which would otherwise happen after deletion

import { strict as assert } from "assert";
import { deleteKey } from "object-delete-key";

assert.deepEqual(
  deleteKey(
    {
      a: { e: [{ b: { c: "d" } }] },
      b: { c: "d" },
    },
    {
      key: "b",
      val: { c: "d" },
      cleanup: false,
    }
  ),
  { a: { e: [{}] } }
);

Wildcards

import { strict as assert } from "assert";
import { deleteKey } from "object-delete-key";

assert.deepEqual(
  deleteKey(
    {
      a: ["beep", "", "c", "boop"],
      bap: "bap",
    },
    {
      key: "b*p",
      only: "array",
    }
  ),
  {
    a: ["", "c"],
    bap: "bap",
  }
);