1.1.1 • Published 3 years ago
dot-prop-ts v1.1.1
dot-prop-ts
Get, set, or delete a property from a nested object using a dot path
This package is heavily inspired on the dot-prop package developed by Sindre Sorhus and has been refactored to typescript so that it can be installed and used without converting your project to ESM module (see issue).
Install
Using NPM
npm install dot-prop-tsUsing yarn
yarn add dot-prop-tsgetProperty
import {getProperty} from 'dot-prop-ts';
// Getter
getProperty({foo: {bar: 'unicorn'}}, 'foo.bar');
//=> 'unicorn'
getProperty({foo: {bar: 'a'}}, 'foo.notDefined.deep');
//=> null
getProperty({foo: {bar: 'a'}}, 'foo.notDefined.deep', 'default value');
//=> 'default value'
getProperty({foo: {'dot.dot': 'unicorn'}}, 'foo.dot\\.dot');
//=> 'unicorn'
getProperty({foo: [{bar: 'unicorn'}]}, 'foo.0.bar');
//=> 'unicorn'setProperty
import {setProperty} from 'dot-prop-ts';
const object = {foo: {bar: 'a'}};
setProperty(object, 'foo.bar', 'b');
//=> {foo: {bar: 'b'}}
const foo = setProperty({}, 'foo.bar', 'c');
//=> {foo: {bar: 'c'}}
setProperty(object, 'foo.baz', 'x');
//=> {foo: {bar: 'b', baz: 'x'}}
setProperty(object, 'foo.biz[0]', 'a');
//=> {foo: {bar: 'b', baz: 'x', biz: ['a']}}hasProperty
import {hasProperty} from 'dot-prop-ts';
const object = {foo: {bar: 'a'}};
hasProperty(object, 'foo.bar');
//=> true
hasProperty(object, 'foo.goo');
//=> falsedeleteProperty
import {deleteProperty} from 'dot-prop-ts';
const object = {foo: {bar: 'a'}};
deleteProperty(object, 'foo.bar');
//=> {foo:{}}
const object = {foo: {bar: 'a'}};
deleteProperty(object, 'foo');
//=> {}