dset

A tiny (160B) utility for safely writing deep Object values~!

  • 所有者: lukeed/dset
  • 平台:
  • 许可证: MIT License
  • 分类:
  • 主题:
  • 喜欢:
    0
      比较:

Github星跟踪图

dset Build Status

A tiny (160B) utility for safely writing deep Object values~!

This module exposes two module definitions:

  • ES Module: dist/dset.es.js
  • CommonJS: dist/dset.js
  • UMD: dist/dset.min.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 };
let qux = { };

dset(foo, 'd.e.f', 'hello');
// or ~> dset(foo, ['d', 'e', 'f'], 'hello');
console.log(foo);
//=> { a:1, b:2, d:{ e:{ f:'hello' } } };

dset(bar, 'bar.1', 999);
// or ~> dset(bar, ['bar', 1], 999);
console.log(bar);
//=> { foo:123, bar:[4, 999, 6], baz:{} };

dset(baz, 'b.x.j.k', 'mundo');
dset(baz, 'b.x.y.z', 'hola');
console.log(baz);
//=> { a:1, b:{ x:{ y:{ z:'hola' }, j:{ k:'mundo' } } }, c:3 }

dset(qux, 'a.0.b.0', 1);
dset(qux, 'a.0.b.1', 2);
console.log(qux);
//=> { a: [{ b: [1, 2] }] }

Mutability

As shown in the examples above, all dset interactions mutate the source object.

If you need immutable writes, please visit clean-set (182B).
Alternatively, you may pair dset with klona, a 366B utility to clone your source(s). Here's an example pairing:

import klona from 'klona';
import dset from 'dset';

export function deepset(obj, path, val) {
  let copy = klona(obj);
  dset(copy, path, val);
  return copy;
}

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.When numerical-types are encounted, Arrays are created instead!

value

Type: Any

The value that you want to set. Can be of any type!

Benchmarks

For benchmark results, check out the bench directory!

  • dlv - safely read from deep properties in 120 bytes
  • dequal - safely check for deep equality in 247 bytes
  • klona - quickly "deep clone" data in 200 to 330 bytes
  • clean-set - fast, immutable version of dset in 182 bytes

License

MIT © Luke Edwards

主要指标

概览
名称与所有者lukeed/dset
主编程语言JavaScript
编程语言JavaScript (语言数: 1)
平台
许可证MIT License
所有者活动
创建于2018-02-20 19:02:16
推送于2024-09-09 15:16:25
最后一次提交2024-09-09 08:16:24
发布数11
最新版本名称v3.1.4 (发布于 2024-09-09 08:16:24)
第一版名称v1.0.0 (发布于 2018-02-21 13:55:50)
用户参与
星数773
关注者数10
派生数25
提交数86
已启用问题?
问题数25
打开的问题数8
拉请求数12
打开的拉请求数1
关闭的拉请求数8
项目设置
已启用Wiki?
已存档?
是复刻?
已锁定?
是镜像?
是私有?