What is dset?
The dset npm package is a tiny utility for safely setting deep values in JavaScript objects. It is designed to be fast and efficient, making it ideal for performance-sensitive applications.
What are dset's main functionalities?
Set deep values
This feature allows you to set a value deep within an object using a dot-separated string path. The dset function will create any necessary intermediate objects.
const dset = require('dset');
let obj = {};
dset(obj, 'a.b.c', 42);
console.log(obj); // { a: { b: { c: 42 } } }
Array index support
dset supports setting values within arrays by using bracket notation in the path string. This allows for complex nested structures involving both objects and arrays.
const dset = require('dset');
let obj = {};
dset(obj, 'a.b[0].c', 42);
console.log(obj); // { a: { b: [ { c: 42 } ] } }
Custom separator
You can specify a custom separator for the path string, allowing for flexibility in how paths are defined.
const dset = require('dset');
let obj = {};
dset(obj, 'a/b/c', 42, '/');
console.log(obj); // { a: { b: { c: 42 } } }
Other packages similar to dset
lodash.set
Lodash is a popular utility library that provides a set function for setting deep values in objects. While lodash.set is more feature-rich and part of a larger library, it is also larger in size compared to dset.
dot-prop
dot-prop is another utility for managing deep properties in JavaScript objects. It offers similar functionality to dset but includes additional features like getting and deleting properties. However, it is slightly larger in size.
set-value
set-value is a utility for setting nested values in objects using dot notation. It is similar in functionality to dset but includes additional options for customizing behavior. It is also larger in size compared to dset.
dset 
A tiny (135B) utlity for safely writing deep Object values~!
This module exposes two module definitions:
- ES Module:
dist/dset.es.js
- CommonJS:
dist/dset.js
For accessing deep object properties, please see dlv
.
Install
$ npm install --save dset
Usage
const dset = require('dset');
let foo = { a:1, b:2 };
let bar = { foo:123, bar:[4, 5, 6], baz:{} };
let baz = { a:1, b:{ x:{ y:{ z:999 } } }, c:3 };
dset(foo, 'd.e.f', 'hello');
console.log(foo);
dset(bar, 'bar.1', 999);
console.log(bar);
dset(baz, 'b.x.j.k', 'mundo');
dset(baz, 'b.x.y.z', 'hola');
console.log(baz);
API
dset(obj, path, val)
Returns: void
obj
Type: Object
The Object to traverse & mutate with a value.
path
Type: String
or Array
The key path that should receive the value. May be in x.y.z
or ['x', 'y', 'z']
formats.
Note: Please be aware that only the last key actually receives the value!
Important: New Objects are created at each segment if there is not an existing structure.
value
Type: Any
The value that you want to set. Can be of any type!
License
MIT © Luke Edwards