https://github.com/privatenumber/chainset
Set object values using property chaining syntax
https://github.com/privatenumber/chainset
chain deep object property set
Last synced: 3 months ago
JSON representation
Set object values using property chaining syntax
- Host: GitHub
- URL: https://github.com/privatenumber/chainset
- Owner: privatenumber
- License: mit
- Created: 2022-07-21T18:52:11.000Z (about 3 years ago)
- Default Branch: develop
- Last Pushed: 2022-07-21T21:21:44.000Z (about 3 years ago)
- Last Synced: 2025-03-18T16:04:05.795Z (7 months ago)
- Topics: chain, deep, object, property, set
- Language: TypeScript
- Homepage:
- Size: 45.9 KB
- Stars: 21
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# chainset
Set object values using property chaining syntax.
Support this project by ⭐️ starring and sharing it. [Follow me](https://github.com/privatenumber) to see what other cool projects I'm working on! ❤️
## Why?
Setting a value on an arbitrary nested path can be cumbersome to do correctly.
For example, `someObject.propA.propB.propC = 'value'` on a potentially empty `someObject` requires a guard for each nested property.
#### Without `chainset`
```ts
const someObject = {}if (!Object.hasOwn(someObject, 'propA')) {
someObject.propA = {}
}if (!Object.hasOwn(someObject.propA, 'propB')) {
someObject.propA.propB = {}
}someObject.propA.propB.propC = 'value'
```#### With `chainset`
```ts
const someObject = chainset()someObject.propA.propB.propC = 'value'
```## Usage
### Create a new object
```ts
import chainset from 'chainset'const object = chainset() // => {}
// Automatically initializes 'propB' & 'propC' to objects
object.propA.propB.propC = 'value'console.log(object)
/*
{
propA: {
propB: {
propC: 'value'
}
}
}
*/
```### Use an existing object
```ts
const object = chainset({
foo: {
bar: {}
}
})// Automatically initializes 'propA' & 'propB' to objects
object.foo.bar.propA.propB = 'value'console.log(object)
/*
{
foo: {
bar: {
propA: {
propB: 'value'
}
}
}
}
*/
```## API
### chainset(object, options)
#### object
Type: `object`Default: `Object.create(null)` (a pure, prototype-less object)
The object to ehance with "chain-setting" support.
#### options
##### deep
Type: `boolean | number`
Default: `true`
How deep to add automatic object initialization support on access. Set to `true` to add support infinitely. Set a number to limit the depth of objects to add support to. Set to `false` to only add support to the immediate object.
##### allowedKeys
Type: `RegExp | (string|RegExp)[] | (path, object) => boolean`
A regular expression pattern, array of strings/patterns, or function that restrict what property names will be initialized on access.
##### defaultObject
Type: `(key?: string) => object`
Default: `() => Object.create(null)`
A function that creates a new object to use when a property is accessed.