update-set
v1.0.4
Published
`update-set` is a path-based setter for building update payloads.
Readme
update-set
update-set is a path-based setter for building update payloads.
Unlike lodash.set, it does not write the raw value to the leaf node. It always stores:
{ __set__: true, __value__: value }This makes it possible to distinguish "this field was explicitly updated" from ordinary object data.
Install
npm install update-setUsage
import set from 'update-set';
const target = {};
set(target, 'profile.name', 'Neo');
console.log(target);
// {
// profile: {
// name: {
// __set__: true,
// __value__: 'Neo'
// }
// }
// }Path semantics
update-set treats dot paths and bracket index paths differently:
import set from 'update-set';
const objectPath = {};
set(objectPath, 'a.2.c', 'value');
// {
// a: {
// 2: {
// c: {
// __set__: true,
// __value__: 'value'
// }
// }
// }
// }
const arrayPath = {};
set(arrayPath, 'a[2].c', 'value');
// {
// a: [
// undefined,
// undefined,
// {
// c: {
// __set__: true,
// __value__: 'value'
// }
// }
// ]
// }a.2.ctreats2as an object key.a[2].ctreats2as an array index.- Array-form paths are supported:
set(target, ['items', 1, 'name'], 'Neo').
Nested updates on wrapped values
If a node has already been wrapped with __set__ and __value__, later nested updates continue inside __value__:
import set from 'update-set';
const target = {};
set(target, 'config', { enabled: false, name: 'demo' });
set(target, 'config.enabled', true);
console.log(target);
// {
// config: {
// __set__: true,
// __value__: {
// enabled: {
// __set__: true,
// __value__: true
// },
// name: 'demo'
// }
// }
// }Notes
set(null, path, value)returnsnulland does nothing.- Quoted numeric bracket indices such as
list["1"].donestill work, but they log a deprecation warning. Preferlist[1].done.
API
declare function set<T extends object>(
object: T,
path: string | number | ReadonlyArray<string | number>,
value: any,
): T;