deep
🐡 Get, set, remove, and test for deeply nested properties
Helps you safely work with nested properties.
Note: set()
and remove()
modify the passed-in object rather than creating a
copy. If you'd rather return a new object each time, there are several other
solutions (unchanged is really good).
Install
Using Yarn:
$ yarn add @blakek/deep
…or using npm:
$ npm i --save @blakek/deep
Usage
import { get, has, remove, set } from '@blakek/deep';
const user = {
id: 'abf87de',
roles: ['alert:create', 'alert:read'],
sites: {
github: {
username: 'blakek'
}
}
};
get(user, 'sites.github.username');
get(user, 'this.does.not.exist');
get(user, 'sites.facebook.username', 'no-account');
get(user, 'roles.0');
has(user, 'sites.github');
has(user, 'sites.twitter');
remove({ a: 42, b: 123 }, 'a');
remove({ a: 42 }, 'nothing.exists.here');
set({ a: 42 }, 'a', 123);
set({ a: 42 }, 'a.b.c', 123);
API
For all these, Path
can be a dot-notation string or array of path parts.
get
function get(object: any, path?: Path, defaultValue?: any): any;
Gets the value for a given path with an optional fallback value.
const user = {
id: 'abf87de',
roles: ['alert:create', 'alert:read']
};
get(user, 'roles.0');
get(user, ['roles', 1]);
get(user, 'does.not.exist', 'fallback');
has
function has(object: any, path: Path): boolean;
Returns true
if a value was found at the given path or false
if nothing was
found.
const product = {
id: 'abf87de',
name: 'Logo T-Shirt',
attributes: {
isCool: undefined,
materials: ['cotton']
}
};
has(product, 'attributes.materials');
has(product, ['avability', 'sizes']);
has(product, 'attributes.isCool');
get(product, 'attributes.isCool', false);
remove
function remove(object: any, path: Path): any;
Removes a value at a path and returns the object.
const user = {
username: 'blakek',
password: 'wouldntyouliketoknow'
};
remove(user, 'password');
remove(user, 'property.does.not.exist');
set
function set(object: any, path: Path, value: any): any;
Sets a value at a path and returns the object.
const user = {
profile: {
bgColor: '#639'
}
};
set(user, 'profile.bgColor', 'tomato');
set(user, 'profile.bgImage', '/images/user.png');
set(user, 'profile', null);
Contributing
Node.js and Yarn are required to work with this project.
To install all dependencies, run:
yarn
Useful Commands
| |
---|
yarn build | Builds the project to ./dist |
yarn format | Format the source following the Prettier styles |
yarn test | Run project tests |
yarn test --watch | Run project tests, watching for file changes |
License
MIT