npm.io
3.0.1 • Published yesterday

shvl

Licence
MIT
Version
3.0.1
Deps
0
Size
8 kB
Vulns
0
Weekly
0
Stars
73

shvl

Get and set dot-notated properties within an object. ~190 bytes min+gzip, zero dependencies.


NPM version Build Status NPM downloads MIT license

PRs Welcome

Sponsored by The Webstronauts

Installation

npm install --save shvl

The UMD build is also available on unpkg, exposing shvl as a global:

<script src="//unpkg.com/shvl/dist/index.umd.js"></script>

Usage

import * as shvl from 'shvl';

let obj = {
	a: {
		b: {
			c: 1,
			d: undefined,
			e: null,
		},
	},
};

// Use dot notation for keys
shvl.set(obj, 'a.b.c', 2);
shvl.get(obj, 'a.b.c') === 2;

// Or use an array as key
shvl.get(obj, ['a', 'b', 'c']) === 2;

// Returns undefined if the path does not exist and no default is specified
shvl.get(obj, 'a.b.c.f') === undefined;

// Pass a third argument to get a fallback instead of undefined
shvl.get(obj, 'a.b.c.f', 'fallback') === 'fallback';

API

get(object, path, default?)

Reads the value at path, a dot-string or an array of keys. Returns default when the path does not resolve, or undefined when no default is given.

set(object, path, value)

Writes value at path, creating intermediate objects along the way, and returns the mutated object.

Safety

set never writes through __proto__ or constructor, so a crafted path like constructor.prototype.polluted cannot reach Object.prototype. The guard compares keys with strict equality rather than a regular expression, so overriding RegExp.prototype.test cannot bypass it.

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributors

Thanks goes to these wonderful people (emoji key):


Robin van der Vleuten


ajenkinski


Matheus Vrech

This project follows the all-contributors specification. Contributions of any kind welcome!

License

The MIT License (MIT). Please see License File for more information.

Keywords