@nixat/set
v0.1.1
Published
A utility function to safely set nested object properties
Readme
@nixat/set
A utility function to safely set nested object properties.
Installation
# Using npm
npm install @nixat/set
# Using yarn
yarn add @nixat/set
# Using pnpm
pnpm add @nixat/setUsage
import { set } from '@nixat/set';
// Basic usage
const obj = { a: { b: { c: 1 } } };
set(obj, 'a.b.c', 2); // => { a: { b: { c: 2 } } }
// Setting new properties
set(obj, 'a.b.d', 3); // => { a: { b: { c: 2, d: 3 } } }
// Using array path
set(obj, ['a', 'b', 'e'], 4); // => { a: { b: { c: 2, d: 3, e: 4 } } }
// Creating nested objects
set({}, 'a.b.c', 42); // => { a: { b: { c: 42 } } }
// Working with arrays
const users = { users: [] };
set(users, 'users.0', { name: 'John' }); // => { users: [{ name: 'John' }] }
set(users, 'users.1.name', 'Jane'); // => { users: [{ name: 'John' }, { name: 'Jane' }] }API
set(obj, path, value)
Sets a value at a given path in an object.
Parameters
obj- The object to modifypath- The path to set the property at, can be a dot-notation string or array of keysvalue- The value to set
Returns
The modified object.
License
MIT
