New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

object-delete-key

Package Overview
Dependencies
Maintainers
1
Versions
192
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

object-delete-key

Delete keys from all arrays or plain objects, nested within anything, by key or by value or by both, and clean up afterwards. Accepts wildcards.

  • 1.5.2
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

object-delete-key

Delete keys from all arrays or plain objects, nested within anything, by key or by value or by both, and clean up afterwards. Accepts wildcards.

Minimum Node version required Repository is on BitBucket Coverage View dependencies as 2D chart Downloads/Month Test in browser Code style: prettier MIT License

Table of Contents

Install

npm i object-delete-key

then,

const deleteKey = require("object-delete-key");
// or
import deleteKey from "object-delete-key";

Here's what you'll get:

TypeKey in package.jsonPathSize
Main export - CommonJS version, transpiled to ES5, contains require and module.exportsmaindist/object-delete-key.cjs.js2 KB
ES module build that Webpack/Rollup understands. Untranspiled ES6 code with import/export.moduledist/object-delete-key.esm.js2 KB
UMD build for browsers, transpiled, minified, containing iife's and has all dependencies baked-inbrowserdist/object-delete-key.umd.js41 KB

⬆ back to top

Deleting

Three modes:

  • Delete all key/value pairs found in any nested plain objects where key equals value.
  • Delete all key/value pairs found in any nested plain objects where key is equal to a certain thing. value doesn't matter.
  • Delete all key/value pairs found in any nested plain objects where value is equal to a certain thing. key doesn't matter.

This library accepts anything as input, including parsed HTML, which is deeply nested arrays of plain objects, arrays and strings. You can feed anything as input into this library - if it's traversable, it will be traversed and searched for your key and/or value in any plain objects.

If you want to delete any nested objects that contain certain key/value pair(s), check out ast-delete-object.

⬆ back to top

API

var result = deleteKey(input, options);

Input arguments are not mutated; this package clones them first before using.

API - Input

Input argumentTypeObligatory?Description
inputWhateveryesAST tree, or object or array or whatever. Can be deeply-nested.
optionsObjectyesOptions object. See its key arrangement below.
options object's keyTypeObligatory?DefaultDescription
{
keyStringno^n/aKey to find and delete.
valWhateverno^n/aKey's value to find and delete. Can be a massively nested AST tree or whatever.
cleanupBooleannotrueShould this package delete any empty carcases of arrays/objects left after deletion?
onlyStringnoanyDefault setting will delete from both arrays and objects. If you want to delete from plain objects only, set this to one of "object-type" values below. If you want to delete keys from arrays only, set this to one of "array-type" values below. In this case "key" means array element's value and "value" is not meant to be used.
}

^ - at least one, key or val must be present.

⬆ back to top

Accepted opts.only values
Interpreted as "array-type"Interpreted as "object-type"Interpreted as "any" type
arrayobjectany
arraysobjectsall
arrobjeverything
arayobboth
arroeither
aeach

whatever

e

If opts.only is set to any string longer than zero characters and is not case-insensitively equal to one of the above, the object-delete-key will throw an error.

I want to relieve users from having to check the documentation for opts.only values.

⬆ back to top

API - Output

This library returns the input with all requested keys/value pairs removed.

Example

// deleting key 'c', with value 'd'
deleteKey(
  {
    a: "b",
    c: "d"
  },
  {
    key: "c",
    val: "d"
  }
);
// => {a: 'b'}
// deleting key 'b' with value ['c', 'd']
// two occurencies will be deleted, plus empty objects/arrays deleted because 4th input is default, true
deleteKey(
  {
    a: { e: [{ b: ["c", "d"] }] },
    b: ["c", "d"]
  },
  {
    key: "b",
    val: ["c", "d"]
  }
);
// => {}

Feed options object's key cleanup: false if you don't want empty arrays/objects removed:

// deleting key 'b' with value ['c', 'd']
// two occurencies will be deleted, but empty carcasses won't be touched:
deleteKey(
  {
    a: { e: [{ b: { c: "d" } }] },
    b: { c: "d" }
  },
  {
    key: "b",
    val: { c: "d" },
    cleanup: false
  }
);
// => {a: {e: [{}]}}

Also, you can delete by key only, for example, delete all key/value pairs where the key is equal to b:

deleteKey(
  {
    a: "a",
    b: "jlfghdjkhkdfhgdf",
    c: [{ b: "weuhreorhelhgljdhflghd" }]
  },
  {
    key: "b"
  }
);
// => { a: 'a' }

You can delete by value only, for example, delete all key/value pairs where the value is equal to whatever:

deleteKey(
  {
    a: "a",
    skldjfslfl: "x",
    c: [{ dlfgjdlkjlfgjhfg: "x" }]
  },
  {
    val: "x"
  }
);
// => { a: 'a' }

The example above didn't specified the cleanup, so this package will delete all empty carcases of objects/arrays by default. When cleanup is off, the result would be this:

deleteKey(
  {
    a: "a",
    skldjfslfl: "x",
    c: [{ dlfgjdlkjlfgjhfg: "x" }]
  },
  {
    val: "x",
    cleanup: false
  }
);
// => {
//   a: 'a',
//   c: [{}] // <<<< observe this
// }

⬆ back to top

Wildcards

Wildcards can be used in keys and/or values. This library feeds inputs to ast-monkey which is doing all the heavy lifting, which, in turn, is using matcher.

const res = deleteKey(
  {
    a: ["beep", "", "c", "boop"],
    bap: "bap"
  },
  {
    key: "b*p",
    only: "array"
  }
);
console.log(
  `${`\u001b[${33}m${`res`}\u001b[${39}m`} = ${JSON.stringify(res, null, 4)}`
);
// => {
//      a: ['', 'c'],
//      bap: 'bap',
//    }

⬆ back to top

Rationale

Object-key deletion libraries like node-dropkey are naïve, expecting objects to be located in the input according to a certain pattern. For example, node-dropkey expects that the input will always be a flat array of plain objects.

But in real life, where we deal with AST trees - nested spaghetti of arrays, plain objects and strings — we can't expect anything. This library accepts anything as an input, and no matter how deeply-nested. Feed it some nested AST's (input), then optionally a key or optionally a value (or both), and you'll get a result with that key/value pair removed from every plain object within the input.

I use this library in email-remove-unused-css to delete empty carcases of style tags without any selectors or empty class attributes in the inline HTML CSS.

⬆ back to top

This library vs. _.omit

OK, but if the input is a plain object, you can achieve the same thing using Lodash _.omit, right?

Right, but ONLY if you don't care about the cleanup of empty arrays and/or plain objects afterwards.

Lodash will only delete keys that you ask, possibly leaving empty stumps.

This library will inteligently delete everything upstream if they're empty things (although you can turn it off passing { cleanup: false } in options object).

Observe how key b makes poof, even though, technically, it was only a stump, having nothing to do with actual finding (besides being its parent):

deleteKey(
  {
    a: "a",
    b: {
      c: "d"
    }
  },
  {
    key: "c"
  }
);
// =>
// {
//   a: 'a'
// }

Lodash won't clean up the stump b:

_.omit(
  {
    a: "a",
    b: {
      c: "d"
    }
  },
  "c"
);
// =>
// {
//   a: 'a',
//   b: {} <------------------- LOOK!
// }

In conclusion, Lodash _.omit is different from this library in that:

  • _.omit will not work on parsed HTML trees, consisting of nested arrays/plain objects
  • _.omit will not clean up any stumps left after the deletion.

If you want to save time, object-delete-key is better than Lodash because former is specialised tool for dealing with AST's.

⬆ back to top

Contributing

  • If you want a new feature in this package or you would like us to change some of its functionality, raise an issue on this repo.

  • If you tried to use this library but it misbehaves, or you need advice setting it up, and its readme doesn't make sense, just document it and raise an issue on this repo.

  • If you would like to add or change some features, just fork it, hack away, and file a pull request. We'll do our best to merge it quickly. Prettier is enabled, so you don't need to worry about the code style.

⬆ back to top

Licence

MIT License (MIT)

Copyright © 2018 Codsen Ltd, Roy Revelt

Keywords

FAQs

Package last updated on 27 Dec 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc