del-key

1.0.3 • Public • Published

Delete Key

Build Status npm version License: MIT

Delete a key from a deeply nested JavaScript object.

Why? start with why

There are a few other libs that already aid in deleting keys from objects. But none of them iteratively deletes the key if one of the nested objects is an array.

The following are the highlights of this delete-key library.

  • Traverses through the exact path for maximum performance. Does not iterate over the keys to detect presence.
  • Support for arrays in object path. Keys will be iteratively removed from each item in the array. (This is where del-key differs from lodash's _.unset() method)
  • Accepts array index in path definition.
  • Mutates the object.

Install

$ npm install --save del-key

Usage

Syntax

deleteKey(obj, pathToDelete)

obj - the object that has the key to be deleted

pathToDelete - the path to the key in the object in string notation

See examples below for more info.

Examples

import deleteKey from 'del-key'; // ES6 style import
// const deleteKey = require('del-key'); // ES5 style import
 
const obj = {
  nestedKey: {
    poorKey: 'hello',
    luckyKey: 'hi'
  }
}
deleteKey(obj, 'nestedKey.poorKey') // =>obj.nestedKey = { luckyKey: 'hi' }
//------------------------------------
 
const obj = {
  nestedArray: [{
    poorKey: 'first hello',
    luckyKey: 'first hi'
  }, {
    poorKey: 'second hello',
    luckyKey: 'second hi'
  }]
}
deleteKey(obj, 'nestedArray[0].poorKey')
// =>obj.nestedArray[0] = { luckyKey: 'first hi' }
// =>obj.nestedArray[1] = { poorKey: 'second hello', luckyKey: 'first hi' }
//------------------------------------
 
const obj = {
  nestedArray: [{
    poorKey: 'first hello',
    luckyKey: 'first hi'
  }, {
    poorKey: 'second hello',
    luckyKey: 'second hi'
  }]
}
deleteKey(obj, 'nestedArray.poorKey') // => iteratively removes poorKey from each item in nestedArray
// =>obj.nestedArray[0] = { luckyKey: 'first hi' }
// =>obj.nestedArray[1] = { luckyKey: 'first hi' }
 

License

MIT © Dineshkumar Pandiyan

Versions

Current Tags

  • Version
    Downloads (Last 7 Days)
    • Tag
  • 1.0.3
    1,259
    • latest

Version History

  • Version
    Downloads (Last 7 Days)
    • Published
  • 1.0.3
    1,259
  • 1.0.2
    0
  • 1.0.1
    0
  • 1.0.0
    0

Package Sidebar

Install

npm i del-key

Weekly Downloads

1,259

Version

1.0.3

License

MIT

Unpacked Size

11.1 kB

Total Files

9

Last publish

Collaborators

  • flexdinesh